Expression in C#

The System.Linq.Expressions namespace contains classes, interfaces and enumerations that enable language-level code expressions to be represented as objects in the form of expression trees. 也就是使用该命名空间中的类可以将一段代码表示为对象。在System.Linq.Expressions中,列举了很多种的表达式,其中包括:BinaryExpression,ConditionalExpression,ConstantExpression,ElementInit,Expression, Expression(TDelegate) ,InvocationExpression,LambdaExpression,ListInitExpression,MemberAssignment,MemberBinding,MemberExpression,MemberInitExpression,MemberListBinding,MemberMemberBinding, MethodCallExpression,NewArrayExpression,NewExpression,ParameterExpression,TypeBinaryExpression,UnaryExpression.
在具体使用之前先特别介绍两个类:Expression, Expression(TDelegate) 。

  • Expression: The abstract class Expression provides the root of a class hierarchy used to model expression trees. Provides the base class from which the classes that represent expression tree nodes are derived. It also contains static (Shared in Visual Basic) factory methods to create the various node types.
  • Expression(TDelegate):Represents a strongly typed lambda expression as a data structure in the form of an expression tree.

Expression的一个子类就是LambdaExpression。然后泛型Expression<TDelegate>类又继承了LambdaExpression, 这看起来容易让人混淆. Expression和Expression<TDelegate>的不同之处在于Expression<TDelegate>依照参数和返回类型严格的指出了表达式是那种类型. 显而易见, 这是由TDelegate参数类型指定的, 其必须是一个委托类型. 例如, 我们的简单加法表达式是一个没有参数并且返回一个int类型的表达式——这与Func<int>匹配, 因为我们可以使用Expression<Func<int>>来以一个静态类型的方式表示该表达式. 我们可以通过使用Expression.Lambda方法来完成这个工作。 该方法拥有大量的重载——我们例子使用了泛型方法, 该方法使用了一个类型参数指出我们想展示的委托类型.
LambdaExpression有一个Compile方法, 可以使用它来创建一个适当类型的委托. 现在该委托可以在普通的方式下被执行, 就像是它是用一个普通的方法或者其他方式来创建的一样。
例子一:

Expression

例子二:

UnaryExpression
原文地址:https://www.cnblogs.com/whyandinside/p/1544622.html