普通方法构造表达式树
static void Main(string[] args)
{
//表达式树的参数
ParameterExpression paramA = Expression.Parameter(typeof(int), "aa");
ParameterExpression paramB = Expression.Parameter(typeof(int), "bb");
//表达式树的主体部分
BinaryExpression be = Expression.Add(paramA, paramB);
//构造表达式树
Expression<Func<int, int, int>> expressionTree = Expression.Lambda<Func<int, int, int>>(be, paramA, paramB);
//分析树结构
//主体部分
BinaryExpression body = (BinaryExpression)expressionTree.Body;
//左节点
ParameterExpression left = (ParameterExpression)be.Left;
//右节点
ParameterExpression right = (ParameterExpression)be.Right;
Console.WriteLine(expressionTree);
Console.WriteLine(body);
Console.WriteLine(left.Name);
Console.WriteLine(right.Name);
Console.ReadKey();
}
利用Lambda表达式构造表达式树
//利用Lambda表达式构造表达式树
Expression<Func<int, int, int>> expressionTree = (a, b) => a + b;
Console.WriteLine(expressionTree);
Console.WriteLine(expressionTree.Body);
var param = expressionTree.Parameters;
foreach (var item in param)
{
Console.WriteLine(item.Name + ":::" + item.Type);
}
将表达式树转换成可执行代码
//利用Lambda表达式构造表达式树
Expression<Func<int, int, int>> expressionTree = (a, b) => a + b;
//生成委托的实例
Func<int, int, int> lambda = expressionTree.Compile();
//执行委托的实例
var result = lambda(1, 2);
Console.WriteLine(result);//3