编译.NET code。在.NET 4? [英] Compiling .NET code in .NET 4?
问题描述
我记得当.NET 4是处于测试阶段有一个开发商,做了一个命令行应用程序,他可以输入C#code到,它会编译上飞code的视频。当时的想法是,编译器现在在.NET语言。
I remember when .NET 4 was in beta there was a video of a developer that made a command-line app that he could type C# code into and it would compile the code on the fly. The idea was that the compiler was now available in the .NET language.
任何人都还记得在哪里,这是?我需要创建一个小的宏语言的应用程序,我很想用C#作为宏语言,但我不知道在哪里可以找到这个库。
Anyone recall where this is? I need to create an application with a small macro language and I would love to use C# as that macro language, but I don't know where to find this library..
推荐答案
您可以使用<一个href="http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharp$c$cprovider.aspx"><$c$c>CSharp$c$cProvider$c$c>类在运行时编译的程序集。
You can use the CSharpCodeProvider
class to compile assemblies at runtime.
您需要做一个样板模板包裹在一个类的静态方法的宏命令。
You'll need to make a boilerplate template to wrap the macro commands in a static method in a 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(); }
}
这篇关于编译.NET code。在.NET 4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!