|
C# 3.0 帶來了強大的基于方法的查詢LINQ。為了開發(fā)者更好更方便的使用LINQ,微軟有隨即引入兩個新特性: Lambda和Expression。Lambda簡單來說就是一個匿名方法的簡略寫法,Expression和Lambda的關(guān)系可以從 下面的一小段代碼看下:(.NET Framework 3.5, 記住引用命名空間System.Linq.Expressions;) 1 //simple express: 2 + 3 2 Expression e = Expression.Add(Expression.Constant(2), Expression.Constant(3)); 3 //lambda express: () => 2 + 3; 4 LambdaExpression l = Expression.Lambda(e, null); 5 //compile to delegate. 6 Delegate d = l.Compile(); 7 //convert to 8 Func<int> f = (Func<int>)d; 9 // 10 11 Console.WriteLine(e); 12 Console.WriteLine(l); 13 Console.WriteLine(d); 14 Console.WriteLine(f());
輸出結(jié)果為下: 1 (2 + 3) 2 () => (2 + 3) 3 System.Func`1[System.Int32] 4 5
第一個就是構(gòu)造了一個簡單的常數(shù)相加表達式, 第二個使用lambda形式表達。 第三個系統(tǒng)把lambda表達式編譯成一個委托,注意這個委托是一個泛型委托形式。 第四個使用委托調(diào)用函數(shù),輸出結(jié)果 2 + 3 = 5,是不是很簡單啊。 下面來一個從上面稍微改進,帶參數(shù)的LINQ表達式: 1 ParameterExpression p = Expression.Parameter(typeof(int), "x"); 2 //expression: x + 3 3 Expression e2 = Expression.Add(p, Expression.Constant(3)); 4 //Lambda: x => x + 3; 5 LambdaExpression l2 = Expression.Lambda(e2, new ParameterExpression[] { p }); 6 Delegate d2 = l2.Compile(); 7 Func<int, int> f2 = (Func<int, int>)d2; 8 9 Console.WriteLine(e2); 10 Console.WriteLine(l2); 11 Console.WriteLine(d2); 12 Console.WriteLine(f2(3));
這個只是多使用了一個ParameterExpression,就是聲明了一個參數(shù)。第一個例子是無參函數(shù),那么這個就是簡單的帶一個參數(shù)的表達式。結(jié)果如下: (x + 3) x => (x + 3) System.Func`2[System.Int32,System.Int32] 6
很簡單吧。 示例代碼:下載
|