【问题标题】:Creating an expression tree that uses a dynamically generated type创建使用动态生成的类型的表达式树
【发布时间】:2014-07-24 16:50:20
【问题描述】:

我有一个完全初始化的MethodBuilderEnumBuilderMethodBuilder 指向动态程序集的入口点。它具有以下签名:

public static int Main (string [] args) {...}

程序集生成代码工作正常,我可以使用Reflection.Emit 对其进行测试。我不想发出 IL,而是想从表达式树中保存目标代码。它应该:

  • 声明一个枚举变量
  • 为其赋值
  • 写入控制台
  • 读取暂停控制台
  • 将枚举值返回为 Int32

表达式树:

// Intention: Declare string [] args in the expression scope.
var arguments = Expression.Parameter(typeof(string []), "args");
// Intention: var code = default(MyDynamicEnum);
var code = Expression.Variable(builderEnum, "code");
// Intention: code = MyDynamicEnum.Two;
var assign = Expression.Assign(code, Expression.Constant(2, builderEnum));
// Intention: Console.WriteLine(args [0]);
var write = Expression.Call(typeof(Console).GetMethod("WriteLine", new Type [] { typeof(string) }), Expression.ArrayIndex(arguments, Expression.Constant(0, typeof(int))));
// Intention: Console.ReadKey(true);
var read = Expression.Call(typeof(Console).GetMethod("ReadKey", new Type [] { typeof(bool) }), Expression.Constant(true, typeof(bool)));
// Intention: return ((int) code);
var @return = Expression.Constant(2, typeof(int));

// How to combine above expressions and create a function body?
var block = Expression.Block(arguments, code, assign, write, read, @return);
var lambda = Expression.Lambda<Func<string [], int>>(block, new ParameterExpression [] { arguments });

lambda.CompileToMethod(builderMethod); // Error: Variable 'code' of type 'Type: MyDynamicEnum' referenced from scope '', but it is not defined.

完整代码可在this GIST 获得。最后一行的错误似乎是有道理的,但我不知道如何解决它。枚举MyDynamicEnum 已经创建为一种类型,但如何将其导入表达式树上下文?任何指针将不胜感激。

【问题讨论】:

    标签: c# .net reflection expression expression-trees


    【解决方案1】:

    使用Expression.Block的正确重载解决了这个问题。

    为了在表达式范围内使用变量,我们必须指定:

    Expression.Block(variables.ToArray(), queue);
    

    其中 variables 是 ParameterExpression 类型的数组。

    【讨论】:

    • 块中的表达式不必在集合中,您可以为它们使用params。只有变量(但不是方法参数!)必须在集合中。
    • @svick:我知道。我的示例很长,因此将不同的段安排到集合(队列)中更方便。
    猜你喜欢
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多