我记得当.NET 4还处于测试阶段时,有一个视频是一位开发人员制作了一个命令行应用程序,他可以在其中输入C#代码,然后它会在运行时编译代码。这个想法是编译器现在可以在.NET语言中使用。
有没有人记得这是哪里?我需要创建一个使用小型宏语言的应用程序,我希望使用C#作为宏语言,但我不知道在哪里可以找到这个库。
发布于 2010-06-24 23:06:28
您可以使用CSharpCodeProvider class在运行时编译程序集。
您需要制作一个样板模板来将宏命令包装在类的静态方法中。
例如:
static readonly Assembly[] References = new[] { typeof(Enumerable).Assembly, typeof(Component).Assembly };
public Action CompileMacro(string source) {
    var options = new CompilerParameters(References.Select(a => a.Location).ToArray()) {
        GenerateInMemory = true
    };
    string fullSource = @"public static class MacroHolder { public static void Execute() { \r\n" + source + "\r\n} }";
    try {
        var compiler = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v4.0" } });
        var results = compiler.CompileAssemblyFromSource(options, fullSource);
        if (results.Errors.Count > 0)
            throw new InvalidOperationException(String.Join(
                Environment.NewLine, 
                results.Errors.Cast<CompilerError>().Select(ce => ce.ErrorText)
            ));
        return (Action)Delegate.CreateDelegate(
            typeof(Action),
            results.CompiledAssembly.GetType("MacroHolder").GetMethod("Execute")
        );
    } finally { options.TempFiles.Delete(); }
}发布于 2010-06-24 23:05:53
我不确定你所指的那个在哪里了,但你正在谈论的是一个交互式Shell。
我记得唯一见过的是Mono团队发布的CSharpRepl。CSharpRepl还包含Mono团队开发的编译器即服务功能。
发布于 2010-06-24 23:17:02
您可以尝试将CS-Script作为替代方案-允许您像运行脚本文件一样运行单个C#文件。
https://stackoverflow.com/questions/3111190
复制相似问题