C#中的表达式树简介

   表达式树是.NET 3.5之后引入的,它是一个强大灵活的工具(比如用在LINQ中构造动态查询)。

    先来看看Expression类的API接口:

using System.Collections.ObjectModel;
 
namespace System.Linq.Expressions
{
    // Summary:
    //     Represents a strongly typed lambda expression as a data structure in the
    //     form of an expression tree. This class cannot be inherited.
    //
    // Type parameters:
    //   TDelegate:
    //     The type of the delegate that the System.Linq.Expressions.Expression<tdelegate>
    //     represents.
    public sealed class Expression<tdelegate> : LambdaExpression
    {
        // Summary:
        //     Compiles the lambda expression described by the expression tree into executable
        //     code.
        //
        // Returns:
        //     A delegate of type TDelegate that represents the lambda expression described
        //     by the System.Linq.Expressions.Expression<tdelegate>.
        public TDelegate Compile();
    }
}

表达式树的语法如下:

Expression<Func<type,returnType>> = (param) => lamdaexpresion;

我们先来看一个简单例子:

Expression<Func<int, int, int>> expr = (x, y) => x+y;

这就是一个表达式树了。使用Expression Tree Visualizer工具(直接调试模式下看也可以,只不过没这个直观)在调试模式下查看这个表达式树(就是一个对象),如下:

可以看到表达式树主要由下面四部分组成:

1、Body 主体部分
2、Parameters 参数部分
3、NodeType 节点类型
4、Lambda表达式类型

 对于前面举的例子,主体部分即x+y,参数部分即(x,y)。Lambda表达式类型是Func<Int32, Int32, Int32>。注意主体部分可以是表达式,但是不能包含语句,如下这样: 

Expression<Func<int, int, int>> expr = (x, y) => { return x+y; };

    会报编译错误“Lambada expression with state body cannot be converted to expression tree”:即带有语句的Lambda表达式不能转换成表达式树。

用前面的方法虽然可以创建表达式树,但是不够灵活,如果要灵活构建表达式树,可以像下面这样:

 

posted on 2016-09-01 06:16  新西兰程序员  阅读(224)  评论(0编辑  收藏  举报