c#系列之各种lambda表达式

时间:2022-07-13 19:08:20

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);};

c#系列之各种lambda表达式