1、常量表达式树
Func<int> compile = (() => 2 + 3);
使用表达式树的方式
ConstantExpression a = Expression.Constant(2); ConstantExpression b = Expression.Constant(3); BinaryExpression add = Expression.Add(a, b); Expression<Func<int>> lambda= Expression.Lambda<Func<int>>(add); Func<int> compile2 = lambda.Compile();
调用
Console.WriteLine(compile());
Console.WriteLine(compile2());
输出结果
要点:
1、ConstantExpression 是常量表达式,通过Expression.Constant(object value)方法创建一个常量表达式
2、BinaryExpression 二元表达式 Expression.Add(Expression left,Expression right)这是加法二元表达式,同理还有Subtract、Multiply和Divide分别对应减、乘和除二元表达式
3、Expression.Lambda<Func<int>>(add)转换成lambda表达式树
4、lambda.Compile()将lambda表达式树转化成委托
2、参数表达式树
lambda表达式
Func<int, int> compile = x=>x+2;
lambda表达式树
ConstantExpression a = Expression.Constant(2); ParameterExpression b = Expression.Parameter(typeof(int),"b"); BinaryExpression add = Expression.Add(a, b); Expression<Func<int,int>> lambda= Expression.Lambda<Func<int,int>>(add,b); Func<int,int> compile2 = lambda.Compile();
注意使用Expression.Lambda方法时,不需要提供常量表达式树
调用
Console.WriteLine(compile(3)); Console.WriteLine(compile2(3));
当left和right都是参数表达式树时
Func<int, int,int> compile = (x,y)=>x+y; ParameterExpression a = Expression.Parameter(typeof(int), "a"); ParameterExpression b = Expression.Parameter(typeof(int),"b"); BinaryExpression add = Expression.Add(a, b); Expression<Func<int,int,int>> lambda= Expression.Lambda<Func<int,int,int>>(add,a,b); Func<int,int, int> compile2 = lambda.Compile(); Console.WriteLine(compile(2,3)); Console.WriteLine(compile2(2,3));