四季花海
lambda是一种函数类型,定义为内联。除了lambda之外,通常还有某种类型的变量,可以保存对函数lambda或其他函数的引用。例如,这里有一段C#代码,它不使用lambda:public Int32 Add(Int32 a, Int32 b){
return a + b;}public Int32 Sub(Int32 a, Int32 b){
return a - b;}public delegate Int32 Op(Int32 a, Int32 b);public void Calculator(Int32 a, Int32 b, Op op){
Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));}public void Test(){
Calculator(10, 23, Add);
Calculator(10, 23, Sub);}它调用Calculator,传递的不只是两个数字,而是调用Calculator内部的哪种方法来获得计算结果。在C#2.0中,我们获得了匿名方法,这些方法将上面的代码缩短为:public delegate Int32 Op(Int32 a, Int32 b);public void Calculator(Int32 a, Int32 b, Op op){
Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));}public void Test(){
Calculator(10, 23, delegate(Int32 a, Int32 b)
{
return a + b;
});
Calculator(10, 23, delegate(Int32 a, Int32 b)
{
return a - b;
});}然后在C#3.0中,我们得到了lambda,这使得代码更短:public delegate Int32 Op(Int32 a, Int32 b);public void Calculator(Int32 a, Int32 b, Op op){
Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));}public void Test(){
Calculator(10, 23, (a, b) => a + b);
Calculator(10, 23, (a, b) => a - b);}