委託、匿名變數、Lambda演變
阿新 • • 發佈:2018-12-29
歷史
2.0之前 委託——>2.0後 匿名變數——>3.0後 Lambda表示式程式碼之間的區別
委託
delegate int calculator(int x, int y); //定義委託 static void Main() { calculator cal = new calculator(Adding); int He = cal(1, 1); Console.Write(He); } // 加法 public static int Adding(int x, int y) { return x + y; }
匿名方法
delegate int calculator(int x, int y); //定義委託
static void Main()
{
calculator cal = delegate(int num1,int num2)
{
return num1 + num2;
};
int he = cal(1, 1);
Console.Write(he);
}
Lambda表示式
delegate int calculator(int x, int y); //定義委託 static void Main() { calculator cal = (x, y) => x + y;//Lambda表示式,很簡潔,Linq類似 int he = cal(1, 1); Console.Write(he); }
Func<T>委託
T 是引數型別,這是一個泛型型別的委託,用起來很方便。說明:從這個例子,我們能看到,p為int型別,j為int型別,返回值為bool型別。static void Main(string[] args) { Func<int, int, bool> gwl = (p, j) => { if (p + j == 10) { return true; } return false; }; Console.WriteLine(gwl(5,5) + ""); //列印‘True’,z對應引數b,p對應引數a Console.ReadKey(); }