【发布时间】:2020-09-29 08:32:25
【问题描述】:
我正试图围绕表达式树进行思考,但遇到了以下我无法解决的问题。我正在尝试生成一个简单的 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
【问题讨论】:
标签: c# lambda expression-trees