来源: C# 表达式树(Expression) – muzizongheng – 博客园
C#中有Expression,即表达式。
通过Expression可以动态构造代码,并编译执行。
比如:
1.
创建参数表达式 :ParameterExpression numParam = Expression.Parameter(typeof(int), “num”);、
创建常量表达式:ConstantExpression five = Expression.Constant(5, typeof(int));
创建比较表达式:BinaryExpression numLessThanFive = Expression.LessThan(numParam, five);
创建标号:LabelTarget label = Expression.Label(typeof(int));
创建循环或者分支表达式:
Expression.Loop( // Adding a conditional block into the loop. Expression.IfThenElse( // Condition: value > 1 Expression.GreaterThan(value, Expression.Constant(1)), // If true: result *= value -- Expression.MultiplyAssign(result, Expression.PostDecrementAssign(value)), // If false, exit the loop and go to the label. Expression.Break(label, result) ), // Label to jump to. label )
2.
创建表达式树:Expression<Func<int, bool>> exprTree = num => num < 5;
3.
分解表达式:ParameterExpression param = (ParameterExpression)exprTree.Parameters[0];
4.
编译表达式:Func<int, bool> result = expr.Compile();
https://muzizongheng.blog.csdn.net/