what
一、定義
Lambda 表達式是一種可用於創建 委托 或 表達式目錄樹 類型的 匿名函數 。通過使用 lambda 表達式,可以寫入可作為參數傳遞或作為函數調用值返回的本地函數。(微軟)
理解
1.Lambda表達式是一種匿名方法。
匿名方法可省略參數列表,Lambda表達式不能省略參數列表的圓括號()
//只需要使用一個delegate關鍵字,加上作為方法的操作使用的代碼塊。 Action printer = delegate { Console.WriteLine("Hello world"); }; printer();
//一個沒有參數的方法,返回值的類型不用指定 系統會自動判斷 () => Console.WriteLine()
二、發展
委托 → 匿名方法 → lambda表達式 → 泛型委托 → 表達式樹
//委托分3步
//step01:用delegate定義一個委托 public delegate int deleFun(int x,int y); //step02:聲明一個方法來對應委托 public static int Add(int x, int y) { return x + y; } static void Main(string[] args) { //step03:用這個方法來實例化這個委托 deleFun dFun = new deleFun(Add); Console.WriteLine(dFun.Invoke(5, 6)); }
//匿名方法分2步 //step01:用delegate定義一個委托 public delegate int deleFun(int x,int y); static void Main(string[] args) { //step02:把一個方法賦值給委托 deleFun dFun = delegate(int x, int y) { return x + y; }; Console.WriteLine(dFun.Invoke(5, 6)); }
//lambda表達式簡化了第2步 //step01:用delegate定義一個委托 public delegate int deleFun(int x,int y); static void Main(string[] args) { //step02:把一個方法賦值給委托 deleFun dFun = (x, y) => {return x + y; }; Console.WriteLine(dFun.Invoke(5, 6)); }
//泛型委托只需要1步 static void Main(string[] args) { //step01:定義泛型委托 並把一個方法賦值給委托 Func<int, int, int> dFun = (x, y) => { return x + y; }; Console.WriteLine(dFun.Invoke(5, 6)); }
說明
在 C# 2.0 中引入了泛型。現在我們能夠編寫泛型類、泛型方法和最重要的:泛型委托。盡管如此,直到 .NET 3.5,微軟才意識到實際上僅通過兩種泛型委托就可以滿足 99% 的需求:
- Action :無輸入參數,無返回值
- Action<T1, ..., T16> :支持1-16個輸入參數,無返回值
- Func<T1, ..., T16, Tout> :支持1-16個輸入參數,有返回值
//表達式樹其實與委托已經沒什么關系了,非要扯上關系,那就這么說吧,表達式樹是存放委托的容器。
//如果非要說的更專業一些,表達式樹是存取Lambda表達式的一種數據結構。要用Lambda表達式的時候,直接從表達式中獲取出來,Compile()就可以直接用了。 static void Main(string[] args) { Expression<Func<int, int, int>> exp = (x, y) => x + y; Func<int, int, int> fun = exp.Compile(); Console.WriteLine(fun.Invoke(5, 6)); }
when
1、列表迭代
List<int> numbers = new List<int>() { 1, 2, 3 };
//一般用法 foreach (int i in numbers) Console.WriteLine(i);
//使用lambda numbers.ForEach(i => Console.WriteLine(i));
2、linq 和lambda
//linq var students1 = from t in db.Students where t.Name == "張三" select new { t.Id, t.Name, t.Age }; //lambda var students2 = db.Students .Where(t => t.Name == "張三") .Select(t => new { t.Id, t.Name, t.Age });
3、線程
4、多態和lambda
5、編寫內聯代碼時
how
語法: 輸入參數(如果有) => 表達式或語句塊
例如:
x => x * x //指定名為 x 的參數並返回 x 的平方值
參考