表达式树
Console.WriteLine("***********************************************"); { //1.0获取方法 MethodInfo method = typeof(string).GetMethod("Substring", new[] { typeof(int), typeof(int) }); //2.0构造表达式树的参数 ParameterExpression target = Expression.Parameter(typeof(string), "s"); ParameterExpression firstParam = Expression.Parameter(typeof(int), "a"); ParameterExpression secondParam = Expression.Parameter(typeof(int), "b"); //3.0构造方法的参数 Expression[] methodArgs = new[] { firstParam, secondParam }; Expression call = Expression.Call(target, method, methodArgs); Console.WriteLine(call);// s.Substring(a,b); //4.0将表达式树的参数构造成 lambda表达式的参数 var lambdaParam = new[] { target, firstParam, secondParam }; foreach (var parameterExpression in lambdaParam) { Console.WriteLine(parameterExpression);//s,a,b } //5.0构造 lambda表达式树 var lambda = Expression.Lambda<Func<string, int, int, string>>(call, lambdaParam); Console.WriteLine(lambda);// (s,a,b)=>s.Substring(a,b); //6.0将 lambda表达式树转换成 lambda表达式 var compile = lambda.Compile(); //7.0执行委托 var result = compile("wjire", 0, 3); Console.WriteLine(result); } Console.WriteLine("***********************************************"); { //1.0获取方法 MethodInfo method = typeof(string).GetMethod("Substring", new[] { typeof(int), typeof(int) }); //2.0构造表达式树的参数 ParameterExpression target = Expression.Parameter(typeof(string), "s"); //2.5设置表达式树的常量 ConstantExpression firstParam = Expression.Constant(0); ConstantExpression secondParam = Expression.Constant(3); //3.0构造方法的参数 Expression[] methodArgs = new[] { firstParam, secondParam }; Expression call = Expression.Call(target, method, methodArgs); Console.WriteLine(call);// s.Substring(0,3); //4.0将表达式树的参数构造成 lambda表达式的参数 var lambdaParam = new[] { target }; foreach (var parameterExpression in lambdaParam) { Console.WriteLine(parameterExpression);//s } //5.0构造 lambda表达式树 var lambda = Expression.Lambda<Func<string, string>>(call, lambdaParam); Console.WriteLine(lambda);// s=>s.Substring(0,3); //6.0将 lambda表达式树转换成 lambda表达式 var compile = lambda.Compile(); //7.0执行委托 var result = compile("wjire"); Console.WriteLine(result); } Console.WriteLine("***********************************************"); { PropertyInfo property = typeof(Person).GetProperty("Id"); var target = Expression.Parameter(typeof(Person), "p"); var pro = Expression.Property(target, property); Console.WriteLine(pro);// p.Id var lambdaParam = new[] { target }; var lambda = Expression.Lambda<Func<Person, int>>(pro, lambdaParam); Console.WriteLine(lambda);// p=>p.Id var compile = lambda.Compile(); var result = compile(new Person { Id = 123 }); Console.WriteLine(result); }