表达式树 - 参数未从 lambda 函数参数映射到表达式参数

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 函数时,我作为参数传递的值似乎不是 'mapped' 和相应的表达式参数 - numParam。在块表达式中,我调用 Console.WriteLine 方法来检查 numParam 的当前值,每次都是 0:

  var isEvenMethod = Generate_IsEven_Func();
  var cond = isEvenMethod(21);
  Console.WriteLine(cond);

  // Prints:
  // 0
  // True

您不应将 numParam 作为第一个参数传递给 Expression.Block(...) 的变量数组中包含 - 现在您实际上是在其中创建一个新的 numParam 变量与传递给 lambda 的 numParam 参数无关的块。由于变量自动初始化为 int (0) 的默认值,这解释了您看到的输出。