Kel*_*lly 5 .net c# compilation
我记得当.NET 4处于测试版时,有一个开发人员的视频制作了一个命令行应用程序,他可以输入C#代码,它会动态编译代码.我们的想法是编译器现在可以在.NET语言中使用.
有谁记得这是什么?我需要用一个小的宏语言创建一个应用程序,我很乐意使用C#作为那种宏语言,但我不知道在哪里可以找到这个库..
SLa*_*aks 11
您可以使用CSharpCodeProvider该类在运行时编译程序集.
您需要创建一个样板模板,将宏命令包装在类中的静态方法中.
例如:
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(); }
}
Run Code Online (Sandbox Code Playgroud)