【问题标题】:Is it possible to dynamically compile and execute C# code fragments within the context of a object/method?是否可以在对象/方法的上下文中动态编译和执行 C# 代码片段?
【发布时间】:2018-08-19 20:15:04
【问题描述】:

这是这个问题的延伸:Is it possible to dynamically compile and execute C# code fragments?

但是是否可以引用某个对象的字段、属性和方法?例如:

public class SomeClass
{
    public int a, b;

    public int SomeMethod(int a, int b, int c)
    {
        return a + b + c;
    }

    public void Execute()
    {
        int c = 3;
        string code = "a = b = 2; int result = SomeMethod(a, b, c);";
        // Compile and execute code here
    }
}

该代码显然在功能方面没有意义,但这只是一个示例。

【问题讨论】:

标签: c# compiler-construction


【解决方案1】:

我不知道有什么方法,但是您可以调用string tmp = Path.GetTempFile() 来创建一个临时文件并执行code = "void Main(string[] args){int a = b = 2; int result = SomeMethod(a, b, c); File.WriteAllBytes(\"" + tmp + "\", BitConverter.GetBytes(result));" 来保存结果。然后你可以用BitConverter.ToInt32(File.ReadAllBytes(tmp))加载它。

【讨论】:

    【解决方案2】:

    我认为您正在寻找诸如 Lambda 表达式序列化器之类的东西 DynamicExpresso

    【讨论】:

      猜你喜欢
      • 2010-10-24
      • 2010-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-06
      相关资源
      最近更新 更多