.NET是否可以在运行时编译和执行新代码?
话虽如此…
我想允许用户在文本框中输入以下任何方程式:
x = x / 2 * 0.07914x = x^2 / 5
并将该等式应用于输入数据点。输入的数据点由
表示,每个数据点由用户指定的方程式处理。我几年前就这样做了,但是我不喜欢该解决方案,因为它需要为每次计算都解析方程的文本:
float ApplyEquation (string equation, float dataPoint){
    // parse the equation string and figure out how to do the math
    // lots of messy code here...
}
当您处理大量数据点时,这会带来很多开销。我希望能够即时将方程式转换为一个函数,以便仅将其解析一次。它看起来像这样:
FunctionPointer foo = ConvertEquationToCode(equation);....
x = foo(x);  // I could then apply the equation to my incoming data like this
函数ConvertEquationToCode将解析方程式,并返回一个指向应用适当数学的函数的指针。
该应用程序基本上将在运行时编写新代码。.NET有可能吗?
回答:
是! 使用在Microsoft.CSharp,System.CodeDom.Compiler和System.Reflection命名空间中找到的方法。这是一个简单的控制台应用程序,它使用一个方法(“
Add42”)编译一个类(“
SomeClass”),然后允许您调用该方法。这是一个简单的示例,我对其进行了格式化,以防止滚动条出现在代码显示中。这只是为了演示在运行时编译和使用新代码。
using Microsoft.CSharp;using System;
using System.CodeDom.Compiler;
using System.Reflection;
namespace RuntimeCompilationTest {
    class Program
    {
        static void Main(string[] args) {
            string sourceCode = @"
                public class SomeClass {
                    public int Add42 (int parameter) {
                        return parameter += 42;
                    }
                }";
            var compParms = new CompilerParameters{
                GenerateExecutable = false, 
                GenerateInMemory = true
            };
            var csProvider = new CSharpCodeProvider();
            CompilerResults compilerResults = 
                csProvider.CompileAssemblyFromSource(compParms, sourceCode);
            object typeInstance = 
                compilerResults.CompiledAssembly.CreateInstance("SomeClass");
            MethodInfo mi = typeInstance.GetType().GetMethod("Add42");
            int methodOutput = 
                (int)mi.Invoke(typeInstance, new object[] { 1 }); 
            Console.WriteLine(methodOutput);
            Console.ReadLine();
        }
    }
}
以上是 .NET是否可以在运行时编译和执行新代码? 的全部内容, 来源链接: utcz.com/qa/402750.html






