动态拼接Lambda表达式-表达式目录树动态构建及修改

动态拼接Lambda表达式-表达式目录树动态构建及修改

访问 :表达式树 Expression<Func<int, int, int>> predicate1 = (m, n) => m * n + 2;
修改:  (m, n) => m * n + 2;改成(m, n) => m * n - 2;

 /// <summary>
        /// 访问 表达式树 Expression<Func<int, int, int>> predicate1 = (m, n) => m * n + 2;
        /// (m, n) => m * n + 2;改成(m, n) => m * n - 2;
        /// </summary>
        public class OperatorExpressionVisitor : ExpressionVisitor
        {
            /// <summary>
            /// 修改表达式树的形式
            /// </summary>
            /// <param name="expression"></param>
            /// <returns></returns>
            public Expression Modify(Expression expression)
            {
                //base.Visit(expression);
                if (expression is BinaryExpression binary)
                {
                    if (binary.NodeType == ExpressionType.Add)
                    {
                        var left = base.Visit(binary.Left); ;
                        var right = base.Visit( binary.Right);
                        var result = Expression.Subtract(left, right);
                        return result;
                    }
                }
                return expression;
            }

            /// <summary>
            /// 表达式树的二元操作
            /// </summary>
            /// <param name="node"></param>
            /// <returns></returns>
            protected override Expression VisitBinary(BinaryExpression node)
            {
                return base.VisitBinary(node);
            }

            /// <summary>
            /// 表达式树的常量操作
            /// </summary>
            /// <param name="node"></param>
            /// <returns></returns>
            protected override Expression VisitConstant(ConstantExpression node)
            {
                return base.VisitConstant(node);
            }
        }

        /// <summary>
        /// 测试表达式树的访问过程
        /// </summary>
        public static void TestDynamicExpressionVisitor()
        {
            Expression<Func<int, int, int>> predicate = (m, n) => m * n + 2;
            //修改之前
            var func1 = predicate.Compile();
            var result1 = func1.Invoke(2, 3);
            Console.WriteLine($"参数2,3");
            Console.WriteLine($"修改---前");
            Console.WriteLine($"body:{predicate.Body}");
            Console.WriteLine($"结果:{result1}");
            OperatorExpressionVisitor visitor = new OperatorExpressionVisitor();
            var expression = visitor.Modify(predicate.Body);
            Expression<Func<int, int, int>> lam = Expression.Lambda<Func<int, int, int>>(expression, predicate.Parameters); 
            var func = lam.Compile();
            var result = func.Invoke(2, 3);
            Console.WriteLine($"修改---后");
            Console.WriteLine($"body:{lam.Body}");
            Console.WriteLine($"结果:{result}");
        }

 

posted @ 2020-12-02 15:35  龙骑科技  阅读(182)  评论(0编辑  收藏  举报