[英]Moq and reflection, passing dynamically generated expression tree / lambda to moq
[英]Creating an expression tree that uses a dynamically generated type
我有一個完全初始化的MethodBuilder
和EnumBuilder
。 MethodBuilder
指向動態程序集的入口點。 它有以下簽名:
public static int Main (string [] args) {...}
程序集生成代碼工作正常,我可以使用Reflection.Emit
來測試它。 我想要從表達式樹中保存目標代碼,而不是發出IL。 這應該:
表達樹:
// 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.
完整代碼可在此GIST上獲得 。 最后一行的錯誤似乎有意義,但我不知道如何解決它。 枚舉MyDynamicEnum
已作為類型創建,但如何將其導入表達式樹上下文? 任何指針將不勝感激。
通過使用Expression.Block
的正確重載解決了它。
為了在表達式范圍中使用變量,我們必須指定:
Expression.Block(variables.ToArray(), queue);
其中variables是ParameterExpression
類型的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.