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

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

问题描述

我想知道是否有可能为C#code片段保存到一个文本文件(或任何输入流),然后执行这些动态?假设是什么提供给我将编译任何的Main()块内精细,是否有可能来编译和/或执行该code?我想preFER编译它性能方面的原因。

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.

最起码,我可以定义他们将需要实现一个接口,那么他们将提供一个code'节'是实现该接口。

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.

推荐答案

在C#中的最佳解决方案/所有静态.NET语言是使用的$c$cDOM 这样的事情。 (作为一个说明,它的另一个主要目的是为了动态构建code,甚至整个班级的位。)

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.)

下面是一个不错的简单例子,从的 LukeH的博客,使用了一些LINQ也只是为了好玩。

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));
    }
}

本类最重要这里是 CSHARP codeProvider ,它利用编译器来编译code的飞行。如果您想要然后运行code,你只需要使用一点反思的动态加载程序集并执行它。

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.

这里是另一个例子C#的(虽然略显不够简明)还向您展示了precisely如何使用的System.Reflection 命名空间来运行的运行编译code。

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#code片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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