在.NET 4中编译.NET代码? [英] Compiling .NET code in .NET 4?

查看:96
本文介绍了在.NET 4中编译.NET代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我记得当.NET 4处于测试阶段时,有一个开发人员制作一个命令行应用程序的视频,他可以键入C#代码,它会在运行时编译代码。想法是编译器现在可以在.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..

推荐答案

您可以使用 CSharpCodeProvider class 在运行时编译程序集。

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 4中编译.NET代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆