是否可以在 .NET 中在运行时编译和执行新代码? [英] Is it possible to compile and execute new code at runtime in .NET?

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

问题描述

注:数学表达式求值不是本题的重点.我想在运行时在 .NET 中编译和执行新代码.话虽如此...

我想允许用户在文本框中输入任何等式,如下所示:

I would like to allow the user to enter any equation, like the following, into a text box:

x = x / 2 * 0.07914
x = x^2 / 5

并将该等式应用于传入的数据点.传入的数据点由 x 表示,每个数据点都由用户指定的方程处理.我几年前就这样做了,但我不喜欢这个解决方案,因为它需要为每次计算解析方程的文本:

And have that equation applied to incoming data points. The incoming data points are represented by x and each data point is processed by the user-specified equation. I did this years ago, but I didn't like the solution because it required parsing the text of the equation for every calculation:

float ApplyEquation (string equation, float dataPoint)
{
    // parse the equation string and figure out how to do the math
    // lots of messy code here...
}

当您处理大量数据点时,这会带来相当多的开销.我希望能够将方程即时转换为函数,以便只需解析一次.它看起来像这样:

When you're processing boatloads of data points, this introduces quite a bit of overhead. I would like to be able to translate the equation into a function, on the fly, so that it only has to be parsed once. It would look something like this:

FunctionPointer foo = ConvertEquationToCode(equation);
....
x = foo(x);  // I could then apply the equation to my incoming data like this

函数 ConvertEquationToCode 将解析方程并返回一个指向应用适当数学的函数的指针.

Function ConvertEquationToCode would parse the equation and return a pointer to a function that applies the appropriate math.

该应用程序基本上会在运行时编写新代码..NET 可以实现吗?

The app would basically be writing new code at run time. Is this possible with .NET?

推荐答案

是的!使用 Microsoft.CSharpSystem.CodeDom.CompilerSystem.Reflection 命名空间.这是一个简单的控制台应用程序,它使用一个方法(Add42")编译一个类(SomeClass"),然后允许您调用该方法.这是一个基本示例,我对其进行了格式化以防止滚动条出现在代码显示中.只是为了演示在运行时编译和使用新代码.

Yes! Using methods found in the Microsoft.CSharp, System.CodeDom.Compiler, and System.Reflection name spaces. Here is a simple console app that compiles a class ("SomeClass") with one method ("Add42") and then allows you to invoke that method. This is a bare-bones example that I formatted down to prevent scroll bars from appearing in the code display. It is just to demonstrate compiling and using new code at run time.

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

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