为了账号安全,请及时绑定邮箱和手机立即绑定

.NET是否可以在运行时编译和执行新代码?

.NET是否可以在运行时编译和执行新代码?

C#
慕仙森 2019-12-13 10:09:09
注意:数学表达式评估不是此问题的重点。我想在.NET运行时编译并执行新代码。 话虽如此...我想允许用户在文本框中输入以下任何方程式:x = x / 2 * 0.07914x = x^2 / 5并将该等式应用于输入数据点。输入的数据点由x表示,每个数据点由用户指定的方程式处理。我几年前就这样做了,但是我不喜欢该解决方案,因为它需要为每次计算都解析方程的文本: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有可能吗?
查看完整描述

3 回答

?
慕森卡

TA贡献1806条经验 获得超8个赞

是! 使用在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();

        }

    }

}



查看完整回答
反对 回复 2019-12-14
  • 3 回答
  • 0 关注
  • 310 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信