lambda表達式說白了就是一個匿名函數。
使用場景,舉個例子吧,就像我自己寫Android程序時,如果要綁定點擊事件,經常要寫一大堆幾乎一樣的格式的代碼,而這些代碼基本上沒有復用,所以也沒辦法寫一個函數啊,類啊來講話過程。
而lambda就是一個折中的辦法,在你寫一個函數,且只用在一個地方的時候,你可以寫這樣一個函數來簡化。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
delegate void test();
delegate void test2(int x);
class Program
{
static void Main(string[] args)
{
test mytest = delegate() { Console.WriteLine("wwx use the first"); };
mytest += ()=> {Console.WriteLine("wwx use the second");};
test2 mytest2 = delegate(int x) { Console.WriteLine("wwx use the first use the {0}",x);};
mytest2 += (x) => {Console.WriteLine("wwx use the second use the {0}",x);};
mytest2 += x =>{Console.WriteLine("wwx use the third use the {0}",x);};
mytest2 += x => Console.WriteLine("use the four use the {0}",x);
mytest();
mytest2(2);
}
}
}
有幾個特點,對於只有一個參數的話,甚至可以不寫括號而且如果不是out,ref這樣的參數,可以不加類型(多個變量),如果方法體只有一句話,那么可以不寫大括號。
mytest2 += (x,y) => {Console.WriteLine("wwx use the second use the {0}",x);};
