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

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

问题描述

我想知道是否可以将 C# 代码片段保存到文本文件(或任何输入流)中,然后动态执行它们?假设提供给我的内容可以在任何 Main() 块中编译良好,是否可以编译和/或执行此代码?出于性能原因,我更愿意编译它.

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.

推荐答案

在 C#/所有静态 .NET 语言中的最佳解决方案是使用 CodeDOM 用于此类事情.(注意,它的另一个主要目的是动态构建代码片段,甚至整个类.)

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

这里最重要的类是 CSharpCodeProvider,它利用编译器动态编译代码.如果你想然后运行代码,你只需要使用一点反射来动态加载程序集并执行它.

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# 中的示例(虽然稍微不那么简洁)另外向您展示了如何使用 System.Reflection 命名空间运行运行时编译的代码.

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天全站免登陆