Lambda 表達式是一種可用於建立委託或表達式目錄樹類型的匿名函數。經過使用 lambda 表達式,能夠寫入可做爲參數傳遞或做爲函數調用值返回的本地函數。 Lambda 表達式對於編寫 LINQ 查詢表達式特別有用。若要建立 Lambda 表達式,須要在 Lambda 運算符 => 左側指定輸入參數(若是有),而後在另外一側輸入表達式或語句塊。例如,lambda 表達式 x => x * x 指定名爲 x 的參數並返回 x 的平方值html
using System; namespace NewAttr { /// <summary> /// Lambda 表達式是一種可用於建立委託或表達式目錄樹類型的匿名函數。 /// Lambda 表達式對於編寫 LINQ 查詢表達式特別有用。 /// </summary> public class LambdaDemo { public LambdaDemo() { } /// 委託不能重載,即委託名稱相同,參數類型,個數不一樣。 /// 構造委託的時候,根本無論參數,固然也就不知道你要構造的是哪一個委託。 private delegate int del(int x); private delegate int del2(int x, int s); private delegate void del3(); public static void Test() { del myDel1 = x => x * x; del myDel2 = (x) => x * x; del myDel3 = (x) => x * x; del myDel4 = (int x) => x * x; del myDel5 = (int x) => { return x * x; }; Console.WriteLine("del myDel1 = x => x * x :{0}", myDel1(2)); Console.WriteLine("del myDel2 = (x) => x * x :{0}", myDel2(2)); Console.WriteLine("del myDel3 = (x) => x * x :{0}", myDel3(2)); Console.WriteLine("del myDel4 = (int x) => x * x :{0}", myDel4(2)); Console.WriteLine("del muDel5 = (int x) =>{1}:{0}", myDel5(2), " { return x * x; } "); del3 myDel6 = () => Test2(); Console.WriteLine("--------------------------------"); myDel6(); } public static void Test2() { del2 myDel2 = (x, y) => x * y; del2 myDel3 = (int x, int y) => x * y; del2 myDel4 = (int x, int y) => { return x * y; }; Console.WriteLine("del2 myDel2 = (x, y) => x * y :{0}", myDel2(2, 2)); Console.WriteLine("del2 myDel3 = (int x, int y) => x * y :{0}", myDel3(2, 2)); Console.WriteLine("del2 myDel4 = (int x, int y) => {1} :{0}", myDel4(2, 2), "{ return x * y; }"); Console.WriteLine("--------------------------------"); FunTest(); } public static void FunTest() { ///其中 Func 是最多具備十六個輸入參數的任何一個 Func 委託 ///以後一個爲返回值。 ///Func<TResult>,Func<T,TResult>,Func<T,.....T,TResult> Func<int> myFunc = () => 1; Console.WriteLine("Func<int> myFunc = () => 1 :{0}", myFunc()); Func<int, string, int> myFunc2 = (x, y) => x + y.Length; Console.WriteLine("Func<int, string, int> myFunc = (x, y) => x + y.Length :{0}", myFunc2(1, "jasonhua")); ///其中 Action 是最多具備十六個輸入參數的任何一個 Action 委託 Action myAction = () => { Console.WriteLine("Action myAction :1 * 1"); }; myAction(); Action<int, int> myAction2 = (x, y) => { Console.WriteLine("Action<int, int> myAction2 = (x, y) :{0}", x * y); }; myAction2(1,1); } } }
1. C#高級功能(四)擴展方法和索引函數
2. C#高級功能(三)Action、Func,Tuplespa
3. C#高級功能(二)LINQ 和Enumerable類code
4. C#高級功能(一)Lambda 表達式htm
5. C#中泛型的解釋(object,list,var,dynamic的區別)blog
6. C#中委託索引
7. C#和.NET版本對比get