打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
LINQ与DLR的Expression tree(4):创建静态类型的LINQ表达式树节点 (转 rednaxelafx.javaeye.com)

LINQ与DLR的Expression tree(4):创建静态类型的LINQ表达式树节点

关键字: linq dlr expression tree
(Disclaimer:如果需要转载请先与我联系;文中图片请不要直接链接
作者:RednaxelaFX at rednaxelafx.javaeye.com)

系列文章:
LINQ与DLR的Expression tree(1):简介LINQ与Expression tree
LINQ与DLR的Expression tree(2):简介DLR
LINQ与DLR的Expression tree(3):LINQ与DLR的树的对比
LINQ与DLR的Expression tree(4):创建静态类型的LINQ表达式树节点
LINQ与DLR的Expression tree(5):用lambda表达式表示常见控制结构

系列的前三篇介绍过LINQ与DLR中的expressiontree的概况后,我们对LINQ与DLR所使用的AST的概况和关系应该有一定认识了。既然LINQ Expression tree现在是DLRtree的子集,而DLR能够使用DLR tree来支持动态类型的语言,那么LINQ Expressiontree能不能同样支持动态类型方式的呢?系列接下来的文章就会围绕这个主题,描绘一个从使用LINQ Expressiontree过渡到使用DLR tree的过程。

本篇,我们先来详细看看要自己手工创建一棵LINQ Expression tree大概是个什么样子。

System.Linq.Expressions.Expression类上的工厂方法

在第一篇介绍LINQ Expressiontree的时候提到过,创建节点主要是通过调用Expression类上的静态工厂方法,而不是直接使用具体的Expression类的构造器来完成的。下面直接用代码来演示C#中的一些基本表达式结构是如何用Expressiontree来表示的,并在代码最后的Main()方法里演示一个稍微复杂一点的表达式的构造。

由于代码比较长,下面将分段把代码贴出来。如果用IE浏览提示“脚本可能失去响应”,请不要担心,并选择继续执行脚本。本文的完整代码可以通过附件下载。

常量表达式部分
没什么值得解释的,就是通过Expression.Constant()来表示一个常量。注意一个常量可以是C#里的字面量,如0、1、2.0、"abc"、null等,也可以是任意别的语义上符合“常量”概念的对象。
C#代码
  1. // By RednaxelaFX, 2008-09-07  
  2.   
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq.Expressions;  
  6.   
  7. static class ExpressionTreeSamples {  
  8.  
  9.     #region Constant  
  10.   
  11.     // Represents a constant (such as a literal)  
  12.     static void Constant( ) {  
  13.         // Expression<Func<int>> con = ( ) => 1;  
  14.         Expression<Func<int>> con = Expression.Lambda<Func<int>>(  
  15.             Expression.Constant(  
  16.                 1,            // value  
  17.                 typeofint ) // type  
  18.             ),  
  19.             new ParameterExpression[ ] { }  
  20.         );  
  21.     }  
  22.  
  23.     #endregion  


算术表达式部分
这部分代码演示了+、-、*、/、%、幂、一元-、一元+等运算符在Expression tree中的对应物。需要说明的地方有五点:

1、.NET中算术运算可以抛出OverflowException来表示运算结果溢出(overflow)了,也就是超过了数据类型所能表示的范围。用户可以选择不理会这些异常(unchecked)或者关注这些异常(checked)。C#中默认是unchecked。可以对一个表达式或者一个语句块指定checked与unchecked。与此相应,Expression tree API中也对算术运算(和类型转换运算)提供了checked与unchecked的两个版本。

2、在第二个Add()的例子里,原本的lambda表达式只接受一个参数(y),但在表达式内容中使用了一个自由变量(x)。这个时候如果是由C#编译器来编译,就会自动生成一个私有内部类(这里用CompilerGeneratedDisplayClass来模拟),并将自由变量x变为其成员变量。主要是想通过这个例子来演示自己如何通过创建类似的类来模拟lambda表达式对自由变量的捕获(也就是闭包的功能)。

3、Divide()与DivideDouble()实际上演示的都是Expression.Divide()的使用。特意用两个例子来演示是为了说明无论是整型除法还是浮点数除法,Expression.Divide()都能正确处理。Expressiontree中的其它算术表达式也是同理。

4、C#中没有幂运算符,所以Power()中的lambda表达式是用VB.NET来写的;VB.NET有幂运算符,“^”,不过实际上也是映射到Math.Pow()上的调用而已。

5、UnaryPlus()中演示的lambda表达式实际被C#编译器编译时是不会生成对Expression.UnaryPlus()的调用的,因为这个运算符作用在int上并没有什么意义,只是直接返回其操作数的值而已。但是Expression treeAPI允许用户指定在创建这些算术运算表达式节点时使用什么方法来执行运算,当用户选择使用默认以外的方法时,这个表达式还是可能有不同的意义的。例如这个Expression.UnaryPlus有两个版本的重载:
默认方法:
C#代码
  1. public static UnaryExpression UnaryPlus( Expression expression )  

用户指定方法:
C#代码
  1. public static UnaryExpression UnaryPlus( Expression expression, MethodInfo method )  

采用第二个版本时,根据以下规则判断使用什么方法来实现一元加:
引用
  • 如果 method 不为 null 引用(在 Visual Basic 中为 Nothing),并且它表示带一个参数的非 void static(在 Visual Basic 中为 Shared)方法,则它是节点的实现方法。
  • 如果 expression.Type 为定义一元正运算符的用户定义的类型,则表示此运算符的 MethodInfo 为实现方法。
  • 否则,如果 expression.Type 为数值类型,则实现方法为 null 引用(在 Visual Basic 中为 Nothing)。
C#代码
  1. #region Arithmetic  
  2.   
  3. // "+" operator  
  4. static void Add( ) {  
  5.     // Expression<Func<int, int, int>> add = ( x, y ) => x + y;  
  6.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  7.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  8.     Expression<Func<intintint>> add = Expression.Lambda<Func<intintint>>(  
  9.         Expression.Add(  
  10.             x, // left  
  11.             y  // right  
  12.         ),  
  13.         new ParameterExpression[ ] { x, y }  
  14.     );  
  15. }  
  16.   
  17. // simulates a compiler generated closure class  
  18. private class CompilerGeneratedDisplayClass {  
  19.     public int x;  
  20. }  
  21.   
  22. static void Add( int x ) {  
  23.     // Expression<Func<int, int>> add = y => x + y;  
  24.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  25.     var display = new CompilerGeneratedDisplayClass( );  
  26.     display.x = x;  
  27.     Expression<Func<intint>> add = Expression.Lambda<Func<intint>>(  
  28.         Expression.Add(  
  29.             Expression.Field(  
  30.                 Expression.Constant( display ),  
  31.                 typeof( CompilerGeneratedDisplayClass ).GetField( "x" )  
  32.             ),  
  33.             y  
  34.         ),  
  35.         new ParameterExpression[ ] { y }  
  36.     );  
  37. }  
  38.   
  39. // "+" operator, checked  
  40. static void AddChecked( ) {  
  41.     // Expression<Func<int, int, int>> add = ( x, y ) => checked( x + y );  
  42.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  43.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  44.     Expression<Func<intintint>> add = Expression.Lambda<Func<intintint>>(  
  45.         Expression.AddChecked(  
  46.             x, // left  
  47.             y  // right  
  48.         ),  
  49.         new ParameterExpression[ ] { x, y }  
  50.     );  
  51. }  
  52.   
  53. // "-" operator  
  54. static void Subtract( ) {  
  55.     // Expression<Func<int, int, int>> sub = ( x, y ) => x - y;  
  56.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  57.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  58.     Expression<Func<intintint>> sub = Expression.Lambda<Func<intintint>>(  
  59.         Expression.Subtract(  
  60.             x, // left  
  61.             y  // right  
  62.         ),  
  63.         new ParameterExpression[ ] { x, y }  
  64.     );  
  65. }  
  66.   
  67. // "-" operator, checked  
  68. static void SubtractChecked( ) {  
  69.     // Expression<Func<int, int, int>> sub = ( x, y ) => checked( x - y );  
  70.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  71.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  72.     Expression<Func<intintint>> sub = Expression.Lambda<Func<intintint>>(  
  73.         Expression.SubtractChecked(  
  74.             x, // left  
  75.             y  // right  
  76.         ),  
  77.         new ParameterExpression[ ] { x, y }  
  78.     );  
  79. }  
  80.   
  81. // "*" operator  
  82. static void Multiply( ) {  
  83.     // Expression<Func<int, int, int>> mul = ( x, y ) => x * y;  
  84.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  85.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  86.     Expression<Func<intintint>> mul = Expression.Lambda<Func<intintint>>(  
  87.         Expression.Multiply(  
  88.             x, // left  
  89.             y  // right  
  90.         ),  
  91.         new ParameterExpression[ ] { x, y }  
  92.     );  
  93. }  
  94.   
  95. // "*" operator, checked  
  96. static void MultiplyChecked( ) {  
  97.     // Expression<Func<int, int, int>> mul = ( x, y ) => checked( x * y );  
  98.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  99.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  100.     Expression<Func<intintint>> mul = Expression.Lambda<Func<intintint>>(  
  101.         Expression.MultiplyChecked(  
  102.             x, // left  
  103.             y  // right  
  104.         ),  
  105.         new ParameterExpression[ ] { x, y }  
  106.     );  
  107. }  
  108.   
  109. // "/" operator (demonstrates integral division)  
  110. static void Divide( ) {  
  111.     // Expression<Func<int, int, int>> div = ( x, y ) => x / y;  
  112.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  113.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  114.     Expression<Func<intintint>> div = Expression.Lambda<Func<intintint>>(  
  115.         Expression.Divide(  
  116.             x, // left  
  117.             y  // right  
  118.         ),  
  119.         new ParameterExpression[ ] { x, y }  
  120.     );  
  121. }  
  122.   
  123. // // "+" operator (demonstrates floating-point division)  
  124. static void DivideDouble( ) {  
  125.     // Note that this expression tree has exactly the same shape as the one  
  126.     // in Divide(). The only difference is the type of parameters and result.  
  127.     // The expression tree can find correct implementation of the divide operator  
  128.     // in both cases.  
  129.   
  130.     // Expression<Func<double, double, double>> div = ( x, y ) => x / y;  
  131.     ParameterExpression x = Expression.Parameter( typeofdouble ), "x" );  
  132.     ParameterExpression y = Expression.Parameter( typeofdouble ), "y" );  
  133.     Expression<Func<doubledoubledouble>> div = Expression.Lambda<Func<doubledoubledouble>>(  
  134.         Expression.Divide(  
  135.             x, // left  
  136.             y  // right  
  137.         ),  
  138.         new ParameterExpression[ ] { x, y }  
  139.     );  
  140. }  
  141.   
  142. // "%" operator  
  143. static void Modulo( ) {  
  144.     // Expression<Func<int, int, int>> mod = ( x, y ) => x % y;  
  145.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  146.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  147.     Expression<Func<intintint>> mod = Expression.Lambda<Func<intintint>>(  
  148.         Expression.Modulo(  
  149.             x, // left  
  150.             y  // right  
  151.         ),  
  152.         new ParameterExpression[ ] { x, y }  
  153.     );  
  154. }  
  155.   
  156. // exponentiation operator (not available in C#)  
  157. static void Power( ) {  
  158.     // There‘s no "raise to the power" operator in C#, but there is one  
  159.     // in VB.NET, the "^" operator.  
  160.     // So this sample is in VB9:  
  161.     // Dim pow As Expression(Of Func(Of Integer, Integer, Integer)) _  
  162.     //     = Function( x, y ) x ^ y  
  163.   
  164.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  165.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  166.     Expression<Func<intintint>> pow = Expression.Lambda<Func<intintint>>(  
  167.         Expression.Power(  
  168.             x, // left  
  169.             y  // right  
  170.         ),  
  171.         new ParameterExpression[ ] { x, y }  
  172.     );  
  173. }  
  174.   
  175. // unary "-" operator  
  176. static void Negate( ) {  
  177.     // Expression<Func<int, int>> neg = x => -x;  
  178.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  179.     Expression<Func<intint>> neg = Expression.Lambda<Func<intint>>(  
  180.         Expression.Negate(  
  181.             x // expression  
  182.         ),  
  183.         new ParameterExpression[ ] { x }  
  184.     );  
  185. }  
  186.   
  187. // unary "-" operator, checked  
  188. static void NegateChecked( ) {  
  189.     // Expression<Func<int, int>> neg = x => checked( -x );  
  190.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  191.     Expression<Func<intint>> neg = Expression.Lambda<Func<intint>>(  
  192.         Expression.NegateChecked(  
  193.             x // expression  
  194.         ),  
  195.         new ParameterExpression[ ] { x }  
  196.     );  
  197. }  
  198.   
  199. // unary "+" operator  
  200. static void UnaryPlus( ) {  
  201.     // Note that C# compiler will optimize this by removing the unary plus  
  202.     //Expression<Func<int, int>> unary = x => +x;  
  203.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  204.     Expression<Func<intint>> unaryPlus = Expression.Lambda<Func<intint>>(  
  205.         Expression.UnaryPlus(  
  206.             x // expression  
  207.         ),  
  208.         new ParameterExpression[ ] { x }  
  209.     );  
  210. }  
  211.  
  212. #endregion  


按位运算表达式部分
有两点需要说明:

1、C#中(以及.NET Framework的基础类库(BCL)中没有逻辑右移运算符“>>>”,而Java、JavaScript等语言中是存在这个运算符的。

2、千万要注意,Expression.And()Expression.Or()是表示按位运算用的,而Expression.AndAlso()Expression.OrElse()才是表示逻辑运算的。
C#代码
  1. #region Bitwise  
  2.   
  3. // "<<" operator  
  4. static void LeftShift( ) {  
  5.     // Expression<Func<int, int, int>> lshift = ( x, y ) => x << y;  
  6.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  7.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  8.     Expression<Func<intintint>> lshift = Expression.Lambda<Func<intintint>>(  
  9.         Expression.LeftShift(  
  10.             x, // left  
  11.             y  // right  
  12.         ),  
  13.         new ParameterExpression[ ] { x, y }  
  14.     );  
  15. }  
  16.   
  17. // ">>" operator  
  18. static void RightShift( ) {  
  19.     // Expression<Func<int, int, int>> rshift = ( x, y ) => x >> y;  
  20.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  21.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  22.     Expression<Func<intintint>> expression = Expression.Lambda<Func<intintint>>(  
  23.         Expression.RightShift(  
  24.             x, // left  
  25.             y  // right  
  26.         ),  
  27.         new ParameterExpression[ ] { x, y }  
  28.     );  
  29.   
  30.     // Note that C# doesn‘t have a logical right shift operator ">>>",  
  31.     // neither is there one in the expression tree  
  32. }  
  33.   
  34. // "&" operator  
  35. static void And( ) {  
  36.     // Note that And() is for bitwise and, and AndAlso() is for logical and.  
  37.   
  38.     // Expression<Func<int, int, int>> and = ( x, y ) => x & y;  
  39.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  40.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  41.     Expression<Func<intintint>> and = Expression.Lambda<Func<intintint>>(  
  42.         Expression.And(  
  43.             x, // left  
  44.             y  // right  
  45.         ),  
  46.         new ParameterExpression[ ] { x, y }  
  47.     );  
  48. }  
  49.   
  50. // "|" operator  
  51. static void Or( ) {  
  52.     // Note that Or() is for bitwise or, and OrElse() is for logical or.  
  53.   
  54.     // Expression<Func<int, int, int>> or = ( x, y ) => x | y;  
  55.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  56.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  57.     Expression<Func<intintint>> or = Expression.Lambda<Func<intintint>>(  
  58.         Expression.Or(  
  59.             x,  
  60.             y  
  61.         ),  
  62.         new ParameterExpression[ ] { x, y }  
  63.     );  
  64. }  
  65.   
  66. // "^" operator  
  67. static void ExclusiveOr( ) {  
  68.     // Expression<Func<int, int, int>> xor = ( x, y ) => x ^ y;  
  69.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  70.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  71.     Expression<Func<intintint>> xor = Expression.Lambda<Func<intintint>>(  
  72.         Expression.ExclusiveOr(  
  73.             x, // left  
  74.             y  // right  
  75.         ),  
  76.         new ParameterExpression[ ] { x, y }  
  77.     );  
  78. }  
  79.  
  80. #endregion  


条件表达式部分
也就是C-like语言中常见的三元运算符“? :”。注意这个对应的不是if-else语句,而是条件表达式——C-like语言中表达式有值,语句不一定有(即便有值也被忽略了);条件表达式的两个分支的值的类型必须匹配。
C#代码
  1. #region Conditional  
  2.   
  3. // "? :" operator  
  4. static void Condition( ) {  
  5.     // Expression<Func<bool, int, int, int>> cond = ( c, x, y ) => c ? x : y;  
  6.     ParameterExpression c = Expression.Parameter( typeofbool ), "c" );  
  7.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  8.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  9.     Expression<Func<boolintintint>> cond = Expression.Lambda<Func<boolintintint>>(  
  10.         Expression.Condition(  
  11.             c, // test  
  12.             x, // if true  
  13.             y  // if false  
  14.         ),  
  15.         new ParameterExpression[ ] { c, x, y }  
  16.     );  
  17. }  
  18.  
  19. #endregion  


相等性表达式部分
也就是等于大于小于等比较大小的部分。比较直观,不多说。
C#代码
  1. #region Equality  
  2.   
  3. // "==" operator  
  4. static void Equal( ) {  
  5.     // Expression<Func<int, int, bool>> eq = ( x, y ) => x == y;  
  6.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  7.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  8.     Expression<Func<intintbool>> eq = Expression.Lambda<Func<intintbool>>(  
  9.         Expression.Equal(  
  10.             x, // left  
  11.             y  // right  
  12.         ),  
  13.         new ParameterExpression[ ] { x, y }  
  14.     );  
  15. }  
  16.   
  17. // "!=" operator  
  18. static void NotEqual( ) {  
  19.     // Expression<Func<int, int, bool>> neq = ( x, y ) => x != y;  
  20.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  21.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  22.     Expression<Func<intintbool>> neq = Expression.Lambda<Func<intintbool>>(  
  23.         Expression.NotEqual(  
  24.             x, // left  
  25.             y  // right  
  26.         ),  
  27.         new ParameterExpression[ ] { x, y }  
  28.     );  
  29.   
  30.     // Note that the lambda above isn‘t equivalent to the following:  
  31.     // Expression<Func<int, int, bool>> neq2 = ( x, y ) => !( x == y );  
  32. }  
  33.   
  34. // ">" operator  
  35. static void GreaterThan( ) {  
  36.     // Expression<Func<int, int, bool>> gt = ( x, y ) => x > y;  
  37.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  38.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  39.     Expression<Func<intintbool>> gt = Expression.Lambda<Func<intintbool>>(  
  40.         Expression.GreaterThan(  
  41.             x, // left  
  42.             y  // right  
  43.         ),  
  44.         new ParameterExpression[ ] { x, y }  
  45.     );  
  46. }  
  47.   
  48. // ">=" operator  
  49. static void GreaterThanOrEqual( ) {  
  50.     // Expression<Func<int, int, bool>> ge = ( x, y ) => x >= y;  
  51.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  52.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  53.     Expression<Func<intintbool>> ge = Expression.Lambda<Func<intintbool>>(  
  54.         Expression.GreaterThanOrEqual(  
  55.             x, // left  
  56.             y  // right  
  57.         ),  
  58.         new ParameterExpression[ ] { x, y }  
  59.     );  
  60. }  
  61.   
  62. // "<" operator  
  63. static void LessThan( ) {  
  64.     // Expression<Func<int, int, bool>> lt = ( x, y ) => x < y;  
  65.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  66.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  67.     Expression<Func<intintbool>> lt = Expression.Lambda<Func<intintbool>>(  
  68.         Expression.LessThan(  
  69.             x, // left  
  70.             y  // right  
  71.         ),  
  72.         new ParameterExpression[ ] { x, y }  
  73.     );  
  74. }  
  75.   
  76. // "<=" operator  
  77. static void LessThanOrEqual( ) {  
  78.     // Expression<Func<int, int, bool>> le = ( x, y ) => x <= y;  
  79.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  80.     ParameterExpression y = Expression.Parameter( typeofint ), "y" );  
  81.     Expression<Func<intintbool>> le = Expression.Lambda<Func<intintbool>>(  
  82.         Expression.LessThanOrEqual(  
  83.             x, // left  
  84.             y  // right  
  85.         ),  
  86.         new ParameterExpression[ ] { x, y }  
  87.     );  
  88. }  
  89.  
  90. #endregion  


关系表达式部分
基本上只要注意好与前面按位运算的And()、Or()区分开就行。另外需要记住的是,Expression.AndAlso()与Expression.OrElse()的默认语义与C#/C++中的&&、||一样,是短路表达式——会根据对左操作数求值的结果决定是否对右操作数求值。
C#代码
  1. #region Relational  
  2.   
  3. // "&&" operator  
  4. static void AndAlso( ) {  
  5.     // Note that And() is for bitwise and, and AndAlso() is for logical and.  
  6.     // Note also that the shortcut semantics is implemented with AndAlso().  
  7.   
  8.     // Expression<Func<bool, bool, bool>> and = ( x, y ) => x && y;  
  9.     ParameterExpression x = Expression.Parameter( typeofbool ), "x" );  
  10.     ParameterExpression y = Expression.Parameter( typeofbool ), "y" );  
  11.     Expression<Func<boolboolbool>> and = Expression.Lambda<Func<boolboolbool>>(  
  12.         Expression.AndAlso(  
  13.             x, // left  
  14.             y  // right  
  15.         ),  
  16.         new ParameterExpression[ ] { x, y }  
  17.     );  
  18. }  
  19.   
  20. // "||" operator  
  21. static void OrElse( ) {  
  22.     // Note that Or() is for bitwise or, and OrElse() is for logical or.  
  23.     // Note also that the shortcut semantics is implemented with OrElse().  
  24.   
  25.     // Expression<Func<bool, bool, bool>> or = ( x, y ) => x || y;  
  26.     ParameterExpression x = Expression.Parameter( typeofbool ), "x" );  
  27.     ParameterExpression y = Expression.Parameter( typeofbool ), "y" );  
  28.     Expression<Func<boolboolbool>> or = Expression.Lambda<Func<boolboolbool>>(  
  29.         Expression.OrElse(  
  30.             x, // left  
  31.             y  // right  
  32.         ),  
  33.         new ParameterExpression[ ] { x, y }  
  34.     );  
  35. }  
  36.   
  37. // "!" operator  
  38. static void Not( ) {  
  39.     // Expression<Func<bool, bool>> or = b => !b;  
  40.     ParameterExpression b = Expression.Parameter( typeofbool ), "b" );  
  41.     Expression<Func<boolbool>> not = Expression.Lambda<Func<boolbool>>(  
  42.         Expression.Not(  
  43.             b // expression  
  44.         ),  
  45.         new ParameterExpression[ ] { b }  
  46.     );  
  47. }  
  48.  
  49. #endregion  


类型转换表达式部分
注意点就在于.NET中的值类型(value type)只能用C-style的类型转换,所以也只能对应Expression.Convert();而引用类型(reference type)既可以用C-style的也可以用as运算符来做类型转换,可以根据需要选用Expression.Convert()或者Expression.TypeAs()。

对了,对C#不熟悉的人可能对??运算符感到陌生。这个运算符的语义是:当左操作数不为null时,该表达式的值为左操作数的值;反之则为右操作数的值。
C#代码
  1. #region Type Conversion  
  2.   
  3. // C-style conversion  
  4. static void Convert( ) {  
  5.     // Expression<Func<int, short>> conv = x => ( short ) x;  
  6.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  7.     Expression<Func<intshort>> conv = Expression.Lambda<Func<intshort>>(  
  8.         Expression.Convert(  
  9.             x,              // expression  
  10.             typeofshort ) // type  
  11.         ),  
  12.         new ParameterExpression[ ] { x }  
  13.     );  
  14. }  
  15.   
  16. // C-style conversion, checked  
  17. static void ConvertChecked( ) {  
  18.     // Expression<Func<int, short>> conv = x => checked( ( short ) x );  
  19.     ParameterExpression x = Expression.Parameter( typeofint ), "x" );  
  20.     Expression<Func<intshort>> conv = Expression.Lambda<Func<intshort>>(  
  21.         Expression.ConvertChecked(  
  22.             x,              // expression  
  23.             typeofshort ) // type  
  24.         ),  
  25.         new ParameterExpression[ ] { x }  
  26.     );  
  27. }  
  28.   
  29. // "as" operator  
  30. static void TypeAs( ) {  
  31.     // Expression<Func<string, object>> typeAs = x => x as object;  
  32.     ParameterExpression x = Expression.Parameter( typeofstring ), "x" );  
  33.     Expression<Func<stringobject>> typeAs = Expression.Lambda<Func<stringobject>>(  
  34.         Expression.TypeAs(  
  35.             x,               // expression  
  36.             typeofobject ) // type  
  37.         ),  
  38.         new ParameterExpression[ ] { x }  
  39.     );  
  40. }  
  41.   
  42. // "is" operator  
  43. static void TypeIs( ) {  
  44.     // Expression<Func<string, bool>> typeIs = x => x is object;  
  45.     ParameterExpression x = Expression.Parameter( typeofstring ), "x" );  
  46.     Expression<Func<stringbool>> typeIs = Expression.Lambda<Func<stringbool>>(  
  47.         Expression.TypeIs(  
  48.             x,               // expression  
  49.             typeofobject ) // type  
  50.         ),  
  51.         new ParameterExpression[ ] { x }  
  52.     );  
  53. }  
  54.   
  55. // "??" operator  
  56. static void Coalesce( ) {  
  57.     // Expression<Func<int?, int>> coal = x => x ?? 1;  
  58.     ParameterExpression x = Expression.Parameter( typeofint? ), "x" );  
  59.     Expression<Func<int?, int>> coal = Expression.Lambda<Func<int?, int>>(  
  60.         Expression.Coalesce(  
  61.             x,                                      // left  
  62.             Expression.Constant( 1, typeofint ) ) // right  
  63.         ),  
  64.         new ParameterExpression[ ] { x }  
  65.     );  
  66. }  
  67.  
  68. #endregion  


成员表达式部分
这里的“成员”主要是指域(field)和属性(property)了。
在演示Expression.Field()的时候我用了前面模拟编译器生成的内部类,只是图个方便而已,因为实在想不到.NET基础类库里(特别是System命名空间里)有什么类型会包含共有域并且该域不是常量的。Int32.MaxValue是一个公有域,但同时也是个常量,C#编译器一编译就把lambda表达式里的域访问优化成一个常量了。所以干脆用一个自定义的类来演示域访问表达式。
Expression treeAPI里除了Expression.Field()和Expression.Property(),还有一个Expression.PropertyOrField()工厂方法。但我没想出来在什么情况下无法得知一个名字到底是成员域还是成员属性,所以没写这个对应的例子。
C#代码
  1. #region Member  
  2.   
  3. // Accessing a field  
  4. static void Field( ) {  
  5.     // Reusing the CompilerGeneratedDisplayClass class for demo.  
  6.   
  7.     //Expression<Func<CompilerGeneratedDisplayClass, int>> field = c => c.x;  
  8.     ParameterExpression c = Expression.Parameter(  
  9.         typeof( CompilerGeneratedDisplayClass ), "c" );  
  10.     Expression<Func<CompilerGeneratedDisplayClass, int>> field =  
  11.         Expression.Lambda<Func<CompilerGeneratedDisplayClass, int>>(  
  12.             Expression.Field(  
  13.                 c,  
  14.                 "x"  
  15.             ),  
  16.             new ParameterExpression[ ] { c }  
  17.         );  
  18. }  
  19.   
  20. // Calling a property  
  21. static void Property( ) {  
  22.     // Expression<Func<string, int>> prop = s => s.Length;  
  23.     ParameterExpression s = Expression.Parameter( typeofstring ), "s" );  
  24.     Expression<Func<stringint>> prop = Expression.Lambda<Func<stringint>>(  
  25.         Expression.Property(  
  26.             s,                                       // expression  
  27.             typeofstring ).GetProperty( "Length" ) // property  
  28.         ),  
  29.         new ParameterExpression[ ] { s }  
  30.     );  
  31. }  
  32.  
  33. #endregion  


方法/委托调用表达式部分
有两点需要注意:

1、Expression.Call()对应的是方法调用,而Expression.Invoke()对应的是委托(delegate)的调用。它们在.NET中最大的不同可以说是:一个委托背后的方法可能是某个类上的方法,也可能是一个通过LCG(lightweight codegeneration)生成的方法;后者是不与任何类相关联的,所以调用机制会有点区别。在Expression treeAPI中这个区别就体现为工厂方法的不同。

2、Expression.Call()既对应成员方法的调用,也对应静态方法的调用。调用静态方法时把instance参数设为null。
C#代码
  1. #region Invocation  
  2.   
  3. // Calling a static method  
  4. static void Call( ) {  
  5.     // Note that to call a static method, use Expression.Call(),  
  6.     // and set "instance" to null  
  7.   
  8.     // Expression<Func<string, int>> scall = s => int.Parse( s );  
  9.     ParameterExpression s = Expression.Parameter( typeofstring ), "s" );  
  10.     Expression<Func<stringint>> scall = Expression.Lambda<Func<stringint>>(  
  11.         Expression.Call(  
  12.             null,                      // instance  
  13.             typeofint ).GetMethod(   // method  
  14.                 "Parse"new Type[ ] { typeofstring ) } ),  
  15.             new Expression[ ] { s }    // arguments  
  16.         ),  
  17.         new ParameterExpression[ ] { s }  
  18.     );  
  19. }  
  20.   
  21. // Calling a member method  
  22. static void CallMember( ) {  
  23.     // Note that to call a member method, use Expression.Call(),  
  24.     // and set "instance" to the expression for the instance.  
  25.   
  26.     // Expression<Func<string, string>> mcall = s => s.ToUpper( );  
  27.     ParameterExpression s = Expression.Parameter( typeofstring ), "s" );  
  28.     Expression<Func<stringstring>> mcall = Expression.Lambda<Func<stringstring>>(  
  29.         Expression.Call(  
  30.             s,                                // instance  
  31.             typeofstring ).GetMethod(       // method  
  32.                 "ToUpper"new Type[ ] { } ),  
  33.             new Expression[ ] { }             // arguments  
  34.         ),  
  35.         new ParameterExpression[ ] { s }  
  36.     );  
  37. }  
  38.   
  39. // Invoking a delegate  
  40. static void Invoke( ) {  
  41.     // Note that invoking a delegate is different from calling a method.  
  42.     // Use Expression.Invoke() instead of Expression.Call().  
  43.   
  44.     // Expression<Func<Func<int>, int>> invoc = f => f( );  
  45.     ParameterExpression f = Expression.Parameter( typeof( Func<int> ), "f" );  
  46.     Expression<Func<Func<int>, int>> invoc = Expression.Lambda<Func<Func<int>, int>>(  
  47.         Expression.Invoke(  
  48.             f,                    // expression  
  49.             new Expression[ ] { } // arguments  
  50.         ),  
  51.         new ParameterExpression[ ] { f }  
  52.     );  
  53. }  
  54.  
  55. #endregion  


数组表达式部分
就是对数组下标和数组长度的特殊处理,没什么特别需要注意的。
C#代码
  1. #region Array  
  2.   
  3. // Array index expression ("[]" operator on arrays)  
  4. static void ArrayIndex( ) {  
  5.     // Expression<Func<int[ ], int, int>> aryIdx = ( a, i ) => a[ i ];  
  6.     ParameterExpression a = Expression.Parameter( typeofint[ ] ), "a" );  
  7.     ParameterExpression i = Expression.Parameter( typeofint ), "i" );  
  8.     Expression<Func<int[ ], intint>> aryIdx = Expression.Lambda<Func<int[ ], intint>>(  
  9.         Expression.ArrayIndex(  
  10.             a, // array  
  11.             i  // index  
  12.         ),  
  13.         new ParameterExpression[ ] { a, i }  
  14.     );  
  15. }  
  16.   
  17. // Array length expression (".Length" property on arrays)  
  18. static void ArrayLength( ) {  
  19.     // Expression<Func<int[ ], int>> aryLen = a => a.Length;  
  20.     ParameterExpression a = Expression.Parameter( typeofint[ ] ), "a" );  
  21.     Expression<Func<int[ ], int>> aryLen = Expression.Lambda<Func<int[ ], int>>(  
  22.         Expression.ArrayLength(  
  23.             a // array  
  24.         ),  
  25.         new ParameterExpression[ ] { a }  
  26.     );  
  27. }  
  28.  
  29. #endregion  


新建对象表达式部分
基本上就是对应“new”运算符相关的表达式了。这部分有两点需要注意:

1、与数组相关的两个初始化方法:
Expression.NewArrayBounds()接受的参数是数组的元素类型和数组的尺寸。尺寸可以是一维或多维的,取决于指定数组尺寸的表达式的个数。下面的例子里演示的是一个二维数组。注意到它是一个矩形数组而不是一个“数组的数组”(array-of-array,或者叫jagged array)。
Expression.NewArrayInit()方法对应的是数字的初始化器,例如new int[] { 1, 2, 3 };它接受的参数是数组的元素类型和由初始化表达式组成的数组。

2、Expression.ListInit()并不只是能创建和初始化System.Collections.Generic.List<T>类型的对象。任何能用C#3.0的列表初始化器表示的新建对象表达式都能用Expression.ListInit()表示,例如这个:
C#代码
  1. var hashset = new HashSet<string> {  
  2.     "Alpha""Beta""Charlie"  
  3. };  

要理解这个初始化器实际上被编译器转换为对默认构造器与一系列Add()方法的调用。在使用Expression.ListInit()时这些实际调用必须手工指定。下面的例子很明显:先选择了默认构造器并用一个Expression.New()来调用,然后是一组通过Expression.ElementInit()对Add()方法的调用。能够制定调用的方法自然意味着可以使用Add()以外的方法作为初始化器的内容咯。
C#代码
  1. #region New  
  2.   
  3. // Creating a new object instance  
  4. static void New( ) {  
  5.     // Expression<Func<object>> n = ( ) => new object( );  
  6.     Expression<Func<object>> newObj = Expression.Lambda<Func<object>>(  
  7.         Expression.New(  
  8.             typeofobject ).GetConstructor( new Type[ ] { } ), // constructor  
  9.             new Expression[ ] { }                               // arguments  
  10.         ),  
  11.         new ParameterExpression[ ] { }  
  12.     );  
  13. }  
  14.   
  15. // Creating a new array with specified bounds  
  16. static void NewArrayBounds( ) {  
  17.     // Expression<Func<int[ , ]>> n = ( ) => new int[ 1, 2 ];  
  18.     Expression<Func<int[ , ]>> newArr = Expression.Lambda<Func<int[ , ]>>(  
  19.         Expression.NewArrayBounds(  
  20.             typeofint ),                               // type  
  21.             new Expression[ ] {                          // bounds  
  22.                 Expression.Constant( 1, typeofint ) ),  
  23.                 Expression.Constant( 2, typeofint ) )  
  24.             }  
  25.         ),  
  26.         new ParameterExpression[ ] { }  
  27.     );  
  28. }  
  29.   
  30. // Creating a new array with initializers  
  31. static void NewArrayInit( ) {  
  32.     // Expression<Func<int[ ]>> n = ( ) => new int[ ] { };  
  33.     Expression<Func<int[ ]>> newArrInit = Expression.Lambda<Func<int[ ]>>(  
  34.         Expression.NewArrayInit(  
  35.             typeofint ),        // type  
  36.             new Expression[ ] { } // initializers  
  37.         ),  
  38.         new ParameterExpression[ ] { }  
  39.     );  
  40. }  
  41.   
  42. // Creating a new list with initializers  
  43. static void ListInit( ) {  
  44.     // Expression<Func<List<int>>> n = ( ) => new List<int>( ) { 1, 2 };  
  45.     Expression<Func<List<int>>> linit = Expression.Lambda<Func<List<int>>>(  
  46.         Expression.ListInit(  
  47.             Expression.New(           // new expression  
  48.                 typeof( List<int> ).GetConstructor( new Type[ ] { } ),  
  49.                 new Expression[ ] { }  
  50.             ),  
  51.             new ElementInit[ ] {      // initializers  
  52.                 Expression.ElementInit(  
  53.                     typeof( List<int> ).GetMethod( "Add"new Type[ ] { typeofint ) } ),  
  54.                     new Expression[ ] { Expression.Constant( 1, typeofint ) ) }  
  55.                 ),  
  56.                 Expression.ElementInit(  
  57.                     typeof( List<int> ).GetMethod( "Add"new Type[ ] { typeofint ) } ),  
  58.                     new Expression[ ] { Expression.Constant( 2, typeofint ) ) }  
  59.                 )  
  60.             }  
  61.         ),  
  62.         new ParameterExpression[ ] { }  
  63.     );  
  64. }  
  65.  
  66. #endregion  


成员初始化表达式部分
对应物是C# 3.0中的成员初始化器;最常见的地方莫过于匿名类型的实例的声明了,例如:
C#代码
  1. new { FistName = "John", LastName = "Smith" }  

为了演示方便,这里建了一个简单的内部类。
C#代码
  1. #region Member Initialization  
  2.   
  3. // simulates an anonymous type  
  4. private class DummyClass {  
  5.     public int Value { getset; }  
  6. }  
  7.   
  8. // Creating a new object instance with member initializers  
  9. static void MemberInit( ) {  
  10.     // Expression<Func<DummyClass>> memInit = ( ) => new { Value = 2 };  
  11.     Expression<Func<DummyClass>> minit = Expression.Lambda<Func<DummyClass>>(  
  12.         Expression.MemberInit(  
  13.             Expression.New(  
  14.                 typeof( DummyClass ).GetConstructor( new Type[ ] { } ),  
  15.                 new Expression[ ] { }  
  16.             ),  
  17.             new MemberBinding[ ] {  
  18.                 Expression.Bind(  
  19.                     typeof( DummyClass ).GetProperty( "Value" ),  
  20.                     Expression.Constant( 2, typeofint ) )  
  21.                 )  
  22.             }  
  23.         ),  
  24.         new ParameterExpression[ ] { }  
  25.     );  
  26. }  
  27.  
  28. #endregion  


“引用”表达式部分
这对于许多C#程序员来说或许不是那么直观的内容,不过如果了解Lisp的话就很好解释。Expression.Quote()与Lisp中的quote特殊形式作用相似,作用是不对其操作数求值,而是将其操作数表达式作为结果的值。听起来有点拗口,我也说不太清楚,或许举个例子会容易理解一些。
假如我有一个lambda表达式,
C#代码
  1. Func<int> five = ( ) => 2 + 3;  

然后调用five(),应该得到结果5。
但假如C#里有一种神奇的运算符(这里让我用反单引号来表示),能够阻止表达式的求值,那么下面的lambda表达式:
C#代码
  1. Func<Expression> fiveExpr = ( ) = `( 2 + 3 );  

对fiveExpr()调用后得到的就是表示2+3的BinaryExpression。
这个Expression.Quote()所达到的效果也正是这一点。
C#代码
  1. // Quoting an Expression  
  2. static void Quote( ) {  
  3.     // There‘s no equivalent syntax for quoting an Expression in C#.  
  4.     // The quote UnaryExpression is used for preventing the evaluation  
  5.     // of its operand expression. Semantically, this results in  
  6.     // returning its operand as the result of this unary expression,  
  7.     // as opposed to returning the evaluated value of its operand.  
  8.     //  
  9.     // It‘s rather like the quote special form in Lisp, where  
  10.     // <code>(quote datum)</code> evaluates to <code>datum</code>.  
  11.   
  12.     Expression<Func<BinaryExpression>> quote = Expression.Lambda<Func<BinaryExpression>>(  
  13.         Expression.Quote(  
  14.             Expression.Add(  
  15.                 Expression.Constant( 2.0 ),  
  16.                 Expression.Constant( 3.0 )  
  17.             )  
  18.         ),  
  19.         new ParameterExpression[ ] { }  
  20.     );  
  21.   
  22.     // Func<BinaryExpression> quteFunc = quote.Compile( );  
  23.     // Console.WriteLine( quoteFunc( ) ); // prints (2 + 3)  
  24.     //  
  25.     // In contrast, a normal Expression.Add() without the quote  
  26.     // will return 4 instead:  
  27.     //Expression<Func<int>> add = Expression.Lambda<Func<int>>(  
  28.     //    Expression.Add(  
  29.     //        Expression.Constant( 2.0 ),  
  30.     //        Expression.Constant( 3.0 )  
  31.     //    ),  
  32.     //    new ParameterExpression[ ] { }  
  33.     //);  
  34.     //Func<int> addFunc = add.Compile( );  
  35.     //Console.WriteLine( addFunc( ) ); // prints 5  
  36. }  


未说明的工厂方法
这几个工厂方法主要是用于自定义的表达式的,没有C#的直观的对应物,所以就不在这里说明了。
C#代码
  1. // not listed above:  
  2. //PropertyOrField  : MemberExpression  
  3. //MakeBinary       : BinaryExpression  
  4. //MakeMemberAccess : MemberExpression  
  5. //MakeUnary        : UnaryExpression  


Main()方法。演示一个稍微复杂一点的表达式
这段代码的解释放到代码后。请先阅读代码看看:
C#代码
  1.     static void Main( string[ ] args ) {  
  2.         // Let‘s make a little complex expression tree sample,  
  3.         // equivalent to:  
  4.         //Expression<Func<int[ ], int>> complexExpr =  
  5.         //    array => ( array != null && array.Length != 0 ) ?  
  6.         //        5 * ( 10 + array[ 0 ] ) :  
  7.         //        -1;  
  8.         ParameterExpression array = Expression.Parameter( typeofint[ ] ), "array" );  
  9.         Expression<Func<int[ ], int>> complexExpr = Expression.Lambda<Func<int[ ], int>>(  
  10.             Expression.Condition(  
  11.                 Expression.AndAlso(  
  12.                     Expression.NotEqual(  
  13.                         array,  
  14.                         Expression.Constant(  
  15.                             null  
  16.                         )  
  17.                     ),  
  18.                     Expression.NotEqual(  
  19.                         Expression.ArrayLength(  
  20.                             array  
  21.                         ),  
  22.                         Expression.Constant(  
  23.                             0,  
  24.                             typeofint )  
  25.                         )  
  26.                     )  
  27.                 ),  
  28.                 Expression.Multiply(  
  29.                     Expression.Constant(  
  30.                         5,  
  31.                         typeofint )  
  32.                     ),  
  33.                     Expression.Add(  
  34.                         Expression.Constant(  
  35.                             10,  
  36.                             typeofint )  
  37.                         ),  
  38.                         Expression.ArrayIndex(  
  39.                             array,  
  40.                             Expression.Constant(  
  41.                                 0,  
  42.                                 typeofint )  
  43.                             )  
  44.                         )  
  45.                     )  
  46.                 ),  
  47.                 Expression.Constant(  
  48.                     -1,  
  49.                     typeofint )  
  50.                 )  
  51.             ),  
  52.             new ParameterExpression[ ] { array }  
  53.         );  
  54.   
  55.         // And let‘s see it in action:  
  56.         Func<int[ ], int> func = complexExpr.Compile( );  
  57.         int[ ] arrayArg = new[ ] { 2, 3, 4, 5 };  
  58.         Console.WriteLine( func( arrayArg ) ); // prints 60  
  59.     }  
  60. }  

Main()方法里,我们手工构造了一个由基本表达式组装起来的表达式。当然,我是可以把其中的各个子表达式先分别赋值给变量,避免这种巨大的嵌套调用;不过嵌套调用也有好处,那就是能比较直观的与“树形”联系起来。回顾这个lambda表达式:
C#代码
  1. Expression<Func<int[ ], int>> complexExpr =  
  2.     array => ( array != null && array.Length != 0 ) ?  
  3.         5 * ( 10 + array[ 0 ] ) :  
  4.         -1;  

它对应的抽象语法树(AST)如下图所示。回忆起AST的特征,注意到用于改变表达式优先顺序的括号已经不需要了:

这个AST与实际对Expression上的工厂方法的调用是一一对应的:

(图片缩小了的话请点击放大)
不难看出Expression tree与C#的表达式的关系。

Expression tree的Compile()方法的一个注意点

还是先看一个例子。我们要写一个比较奇怪的lambda表达式,并让它变成一棵Expression tree:
C#代码
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Linq.Expressions;  
  5.   
  6. static class Program {  
  7.     static void Main( string[ ] args ) {  
  8.         Expression<Func<List<int>, IEnumerable<int>>> filter =  
  9.             list => from i in list  
  10.                     where i % 2 == 0  
  11.                     select i;  
  12.         Console.WriteLine( filter );  
  13.         var fooList = new List<int> { 1, 2, 3, 4, 5 };  
  14.         var result = filter.Compile( )( fooList );  
  15.         foreach ( var i in result ) {  
  16.             Console.WriteLine( i );  
  17.         }  
  18.     }  
  19. }  

运行得到:
引用
list => list.Where(i => ((i % 2) = 0))
2
4


注意到那个查询表达式(from...where...select...)会被翻译为扩展方法的调用,所以上面代码里的filter等价于:
C#代码
  1. list => list.Where( i => i % 2 == 0 )  

也就是说lambda表达式里面还嵌套有lambda表达式。
另外注意到List<T>实现了IEnumerable<T>而没有实现IQueryable<T>,所以这个Where()方法是Enumerable类上的。也就是说filter等价于:
C#代码
  1. list => Enumerable.Where<int>( list, i => i % 2 == 0 )  


然后让我们把这棵Expression tree改用手工方式创建:
C#代码
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Linq.Expressions;  
  5.   
  6. static class Program {  
  7.     static void Main( string[ ] args ) {  
  8.         ParameterExpression list = Expression.Parameter(typeof(List<int>), "list");  
  9.         ParameterExpression i = Expression.Parameter(typeof(int), "i");  
  10.         Expression<Func<List<int>, IEnumerable<int>>> filter = Expression.Lambda<Func<List<int>, IEnumerable<int>>>(  
  11.             Expression.Call(  
  12.                 typeof( Enumerable ).GetMethods( )  
  13.                     .First( method => "Where" == method.Name  
  14.                                    && 2 == method.GetParameters( ).Length )  
  15.                     .MakeGenericMethod( new [ ] { typeofint ) } ),  
  16.                 new Expression[ ] {  
  17.                     list,  
  18.                     Expression.Lambda<Func<intbool>>(  
  19.                         Expression.Equal(  
  20.                             Expression.Modulo(  
  21.                                 i,  
  22.                                 Expression.Constant(  
  23.                                     2,  
  24.                                     typeof(int)  
  25.                                 )  
  26.                             ),  
  27.                             Expression.Constant(  
  28.                                 0,  
  29.                                 typeof(int)  
  30.                             )  
  31.                         ),  
  32.                         new [ ] { i }  
  33.                     )  
  34.                 }  
  35.             ),  
  36.             new [ ] { list }  
  37.         );  
  38.         Console.WriteLine( filter );  
  39.         var fooList = new List<int> { 1, 2, 3, 4, 5 };  
  40.         var result = filter.Compile( )( fooList );  
  41.         foreach ( var item in result )  
  42.             Console.WriteLine( item );  
  43.     }  
  44. }  

留意一下我是如何通过反射来得到Enumerable.Where<TSource>>(thisIEnumerable<TSource> source, Func<TSource, bool>predicate)这个方法的MethodInfo的。由于Enumerable.Where()有两个重载,而且都是publicstatic的,我们无法直接调用Type.GetMethod(string)来得到MethodInfo;另外,也无法通过Type.GetMethod(string,Type[])来得到这个MethodInfo,因为它是泛型方法定义的MethodInfo,不方便直接指定类型。结果只好通过参数个数来区分两个Enumerable.Where(),然后创建出Enumerable.Where<int>()的MethodInfo。

注意到,Enumerable.Where<int>()的第二个参数是Func<int, bool>类型的,但我提供的参数数组里的却是Expression<Func<int, bool>>类型的。这样能匹配么?
判断标准很简单,只要参数数组里各项的Expression.Type与实际参数类型匹配就能行。在调用Compile()的时候,即使有嵌套的lambda表达式(转换成Expression tree也就是Expression<TDelegate>)也没问题。
Expression<Func<int, bool>>的Type属性返回的就是Func<int, bool>,与Where()需要的参数类型匹配,OK。

没注意到的话一开始可能会被转晕掉,所以我觉得值得一提。

LINQ Expression tree与静态类型

LINQ Expression tree是静态类型的,上面的例子里我都选用了显式指定类型的版本的API来创建树的节点(特别是Expression.Constant(),其实不指定类型也可以的)。
虽然Expression tree的内容是静态类型的,但仔细观察会发现组装表达式时,参数类型基本上都只要求是Expression或其派生类就行,无法避免在组装时把不匹配的表达式错误的组装到一起。为什么会这样呢?
对编译器有所了解的人应该很清楚,把源代码解析到抽象语法树只是完成了语法分析,之后还需要做语义分析。语义分析就包括了类型检查等工作。表达式的一个重要特征就是可组合性,一个表达式的子表达式可以是任意语法结构的表达式;类型的匹配与否无法通过语法来表现。当我们把一个lambda表达式赋值给一个Expressin<TDelegate>类型的变量时,C#编译器做了类型检查,并且生成了相应的Expressiontree。但当我们手工创建Expressiontree时,我们既获得了创建并组装节点的权利,也承担起了检查类型的义务——C#编译器只知道那些是表示表达式的对象,而无法进一步帮忙检查其中的内容是否匹配。所以,在创建Expression tree时需要额外小心,并且要注意检查实际内容的类型是否匹配。
一般来说这并不是大问题,因为Expression tree一般是由编译器前端所生成的。在生成这棵树之前,编译器就应该负责完成类型检查等工作。

再谈LINQ Expression tree的局限性

LINQ的Expressiontree只能用于表示表达式,而且并不支持C#与VB.NET的所有表达式——与赋值相关的表达式都无法用Expressiontree表示。因此虽然有一元加和一元减这两个一元运算符的对应物,却没有同为一元运算符的递增(++)与递减(--)的对应物。同时,Expressiontree里面也没有“变量”的概念,ParameterExpression只是用来表示参数,而参数的值在实际调用时绑定好之后就不能再改变。

但这些限制并没有降低LINQ Expression tree理论上所能表示的计算逻辑的范围。

1、引用透明性

由于没有“变量”的概念,通过Expression tree定义的表达式本身无法产生副作用,因而只要一棵Expression tree中不包含对外部的有副作用的方法的调用(Invoke/Call),其中的任何子树重复多次产生的值都是一样的。

这种性质被称为引用透明性(referential transparency)。举例来说,假如原本有这样的一组表达式:
Java代码
  1. a = 1  
  2. b = 2  
  3. x = a + b  
  4. y = a - b  
  5. result = x * y - x % y  

请把这些表达式中的符号看成“名字到值的绑定”而不是变量。如果有引用透明性,那么上面的表达式的求值就可以使用所谓“代替模型”(substitution model),可以展开为以下形式而不改变原表达式计算出来的结果:
Java代码
  1. result = (1 + 2) * (1 - 2) - (1 + 2) % (1 - 2)  

同理,当我们实在需要在同一棵Expression tree中多次使用同一个子表达式的计算结果时,只要多次使用同一棵子树即可;既然没有变量来暂时记住中间结果,那么就手动把表达式展开。用Expression tree的例子来说明,那就是:
C#代码
  1. // xPlusY = x + y  
  2. // result = xPlusY * xPlusY  
  3.   
  4. var x = Expression.Parameter( typeofint ), "x" );  
  5. var y = Expression.Parameter( typeofint ), "y" );  
  6. var add = Expression.Add( x, y );  
  7. var result = Expression.Lambda<Func<intintint>>(  
  8.     Expression.Multiply( add, add ),  
  9.     new ParameterExpression[ ] { x, y }  
  10. );  
  11. Console.WriteLine( result.Compile( )( 3, 4 ) ); // prints 49  

(前面已经介绍过Expression tree的工厂方法,这里为了书写方便就不再显式指明变量类型了。)
能够通过代替模型来求值是许多函数式语言的特征之一。求值顺序不影响计算结果,一般有两种求值顺序:如果先求值再代替,称为应用序(applicative order),也叫做紧迫计算(eager evaluation)或者严格求值(strictevaluation);如果先替换在求值,则称为正则序(normal order),也叫做惰性求值(lazyevaluation)或者延迟求值(delayed evaluation)。
在LINQ Expression tree中,因为无法使用变量,也就难以方便的进行严格求值;上面的例子手工展开了表达式,实际上就是模拟了延迟求值的求值过程,在执行效率上会比严格求值要差一些。这虽然不影响计算的能力,但从性能角度看这么做是有负面影响的。

如果一棵Expressiontree中含有对外界的调用,上述的引用透明性就不成立了;我们无法确定一个调用是否含有副作用,所以无法保证不同的求值顺序能得到相同的结果。而这个问题需要特别的注意,因为.NET/CLR的类型系统中没任何有信息能表明一个函数是否有副作用,所以只能悲观的假设包含对外界的调用的Expression tree不满足引用透明性。

2、Lambda表达式

LINQ Expressiontree允许定义与调用lambda表达式,甚至可以在表达式之中嵌套的定义lambda表达式。这奠定了Expressiontree理论上具有接近完备计算能力的基础。所谓“完备”是指图灵完备(Turing-complete)。无类型的lambda演算是图灵完备的,但在C#中lambda表达式需要指明类型,而有些类型通过C#的类型系统难以表示,因此其表达力会比无类型lambda演算要弱一些。
由于C#的类型系统允许定义递归类型,我们可以利用C#的lambda表达式来写递归的函数。同时,方法体只是一个表达式(而不是语句块)的lambda表达式可以用Expression tree表示,也就是说我们可以用Expressiontree来写递归函数。有了递归,原本需要循环的逻辑都能用递归来编写,也就突破了LINQ Expressiontree没有循环结构的限制。下一篇就让我们来看看实例,敬请期待 ^ ^
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C# Lambda表达式详解,及Lambda表达式树的创建
利用C#将Lambda表达式转化成Expression树
C#-表达式树
由浅入深表达式树(一)
Linq之Expression高级篇(常用表达式类型)
打造自己的LINQ Provider(上):Expression Tree揭秘
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服