[英]Expression trees - parameter not mapped from lambda function argument to Expression Parameter
我试图围绕表达式树进行思考,但遇到了以下我无法解决的问题。 我正在尝试生成一个简单的 lambda 函数来检查整数值是否为偶数:
public static Func<int, bool> Generate_IsEven_Func()
{
var numParam = Expression.Parameter(typeof(int), "numParam");
var returnValue = Expression.Variable(typeof(bool), "returnValue");
var consoleWL = typeof(Console).GetMethod(nameof(Console.WriteLine), new[] { typeof(int) });
var body = Expression.Block(
// Scoping the variables
new[] { numParam, returnValue },
// Printing the current value for numParam
Expression.Call(
null,
consoleWL,
numParam
),
// Assign the default value to return
Expression.Assign(returnValue, Expression.Constant(false, typeof(bool))),
// If the numParam is even the returnValue becomes true
Expression.IfThen(
Expression.Equal(
Expression.Modulo(
numParam,
Expression.Constant(2, typeof(int))
),
Expression.Constant(0, typeof(int))
),
Expression.Assign(returnValue, Expression.Constant(true, typeof(bool)))
),
// value to return
returnValue
);
var lambda = Expression.Lambda<Func<int, bool>>(body, numParam).Compile();
return lambda;
}
当我调用新创建的 lambda 函数时,我作为参数传递的值似乎没有与相应的表达式参数 - numParam
“映射”。 在块表达式中,我调用Console.WriteLine
方法来检查numParam
的当前值,并且每次都为 0:
var isEvenMethod = Generate_IsEven_Func();
var cond = isEvenMethod(21);
Console.WriteLine(cond);
// Prints:
// 0
// True
您不应该在作为第一个参数传递给Expression.Block(...)
的变量数组中包含numParam
- 现在您实际上是在块中创建一个新的numParam
变量,该变量与传递的numParam
参数无关到拉姆达。 由于变量使用int
(0) 的默认值自动初始化,这就解释了您看到的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.