创建一个使用动态生成式的前pression树 [英] Creating an expression tree that uses a dynamically generated type

查看:141
本文介绍了创建一个使用动态生成式的前pression树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个完全初始化 MethodBuilder EnumBuilder 。该 MethodBuilder 指向一个动态装配的入口点。它具有以下签名:

I have a fully initialized MethodBuilder and EnumBuilder. The MethodBuilder points to the entry point of a dynamic assembly. It has the following signature:

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

组装代code工作正常,我可以使用 Reflection.Emit的来测试它。相反,白细胞介素发光的,我要保存目标code从EX pression树。它应该:

The assembly generation code works fine and I can use Reflection.Emit to test it. Instead of emitting IL, I want to save the target code from an expression tree. It should:

  • 在声明枚举变量
  • 在为它分配一个值
  • 写入到控制台
  • 读暂停控制台
  • 返回一个枚举值作为一个Int32

EX preSSION树:

// 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.

满code可在这个GIST 。最后一行的错误似乎很有道理,但我不知道如何解决它。枚举 MyDynamicEnum 已创建为一个类型,但我怎么把它导入前pression树背景?任何指针将AP preciated。

The full code is available on this GIST. The error on the last line seems to make sense but I don't know how to fix it. The enumeration MyDynamicEnum is already created as a type but how do I import it into the expression tree context? Any pointers would be appreciated.

推荐答案

通过使用防爆pression.Block正确的重载解决它

为了在EX pression范围内使用变量,我们必须指定:

In order to use variables in the expression scope, we have to specify:

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

,其中的变量是 ParameterEx pression 类型的数组。

这篇关于创建一个使用动态生成式的前pression树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆