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

问题描述

我试图将自己的头缠在表达式树上,我遇到了以下无法解决的问题。我正在尝试生成一个简单的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

解决方法

您不应在要作为numParam的第一个参数传递的变量数组中包含Expression.Block(...)-现在,您实际上是在块中创建一个新的numParam变量与传递给lambda的numParam参数无关。由于该变量会自动使用int(0)的默认值进行初始化,因此可以解释您所看到的输出。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...