首页 > 代码库 > 表达式树基础代码

表达式树基础代码

using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks;using System.Linq.Expressions;namespace TestExpressionLambda{    class ProgramExpression    {        static void Main(string[] args)        {            ExpressionAdd();            ExpressionFromlambda();            ExpressionStartWith();            Console.Read();        }        /// <summary>        /// 最简单的加法表达式树        ///         ///                   根节点        ///                   BanaryExpression        ///                   NodeType = Add        ///                   Type=System.Int32        ///         ///     左叶子                          右叶子        ///     firstArg                        secondArg        ///     ConstantExpression              ConstantExpression        ///     NodeType=Constant               NodeType=Constant        ///     Type=System.Int32               Type=System.Int32        ///     Value=http://www.mamicode.com/3                         Value=2"StartsWith", new[] { typeof(string) });            //取参数表达式:x,y            ParameterExpression x = Expression.Parameter(typeof(string), "x");            ParameterExpression y = Expression.Parameter(typeof(string), "y");            //StartsWith方法需要的参数            Expression[] methodArgs = new[] { y };            //生成调用表达式            MethodCallExpression call = Expression.Call(x, method, y);            var lambdaParameters = new[] { x, y };            //Expression.Lambda方法生成表达式树委托            Expression<Func<string, string, bool>> lambda = Expression.Lambda<Func<string, string, bool>>(call,                lambdaParameters);            //Compile出委托            Func<string, string, bool> func = lambda.Compile();            Console.WriteLine(func("First", "Second"));            Console.WriteLine(func("First", "Fir"));        }    }}

 

表达式树基础代码