是否可以动态编译和执行C#代码片段? [英] Is it possible to dynamically compile and execute C# code fragments?

查看:140
本文介绍了是否可以动态编译和执行C#代码片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以将C#代码片段保存到文本文件(或任何输入流),然后动态执行这些代码片段?假设提供给我什么是在任何Main()块内编译精细,是否可以编译和/或执行此代码?我更喜欢为性能原因编译它。



至少,我可以定义一个接口,他们将需要实现,然后他们将提供一个代码'

$ c $ /所有静态.NET语言的最佳解决方案是使用 CodeDOM 这样的事情。 (注意,它的另一个主要目的是动态构造代码的位,甚至整个类。)



这是一个很好的简短示例,从 LukeH的博客,它使用一些LINQ只是为了有趣。

 使用System; 
using System.Collections.Generic;
using System.Linq;
使用Microsoft.CSharp;
using System.CodeDom.Compiler;

类程序
{
static void Main(string [] args)
{
var csc = new CSharpCodeProvider(new Dictionary< string,string& (){{CompilerVersion,v3.5}});
var parameters = new CompilerParameters(new [] {mscorlib.dll,System.Core.dll,foo.exe,true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@using System.Linq;
class Program {
public static void Main(string [] args){
var q = from i in Enumerable.Range(1,100)
其中i%2 == 0
select i;
}
});
results.Errors.Cast< CompilerError>()。ToList()。ForEach(error => Console.WriteLine(error.ErrorText));
}
}

这里最重要的是 CSharpCodeProvider ,它利用编译器即时编译代码。如果你想运行代码,你只需要使用一些反射动态加载程序集并执行它。



这里是C#中的另一个例子(虽然稍微不太简洁)还显示了如何使用 System.Reflection 命名空间来运行运行时编译的代码。


I was wondering if it is possible to save C# code fragments to a text file (or any input stream), and then execute those dynamically? Assuming what is provided to me would compile fine within any Main() block, is it possible to compile and/or execute this code? I would prefer to compile it for performance reasons.

At the very least, I could define an interface that they would be required to implement, then they would provide a code 'section' that implemented that interface.

解决方案

The best solution in C#/all static .NET languages is to use the CodeDOM for such things. (As a note, its other main purpose is for dynamically constructing bits of code, or even whole classes.)

Here's a nice short example take from LukeH's blog, which uses some LINQ too just for fun.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

class Program
{
    static void Main(string[] args)
    {
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
        parameters.GenerateExecutable = true;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class Program {
              public static void Main(string[] args) {
                var q = from i in Enumerable.Range(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }
}

The class of primary importance here is the CSharpCodeProvider which utilises the compiler to compile code on the fly. If you want to then run the code, you just need to use a bit of reflection to dynamically load the assembly and execute it.

Here is another example in C# that (although slightly less concise) additionally shows you precisely how to run the runtime-compiled code using the System.Reflection namespace.

这篇关于是否可以动态编译和执行C#代码片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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