簡體   English   中英

表達式樹 - 參數未從 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 函數時,我作為參數傳遞的值似乎沒有與相應的表達式參數 - 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM