C# 表达式树(Expression)

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();








posted @ 2013-07-04 09:44  muzizongheng  阅读(...)  评论(...编辑  收藏
如果我们时时忙着展现自己的知识, 将何从忆起成长所需的无知?