创建使用动态生成类型的表达式树

时间:2014-07-24 16:50:20

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

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

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

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

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

EXPRESSION TREE:

// 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已作为类型创建,但如何将其导入表达式树上下文?任何指针都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

使用Expression.Block的正确重载来解决它。

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

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

其中variables是ParameterExpression类型的数组。

相关问题