【发布时间】:2014-07-24 16:50:20
【问题描述】:
我有一个完全初始化的MethodBuilder 和EnumBuilder。 MethodBuilder 指向动态程序集的入口点。它具有以下签名:
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