//lambda表达式是什么? 左边是参数列表 goes to语法 右边是方法体,本质就是一个方法 // lambda不是委托,因为委托是一个类型 // 也不是委托的实例,因为这里省略了 new 委托() // 他的作用:是一个方法 // 编译后:lambda 实际上会生成一个类中类里面的一个internal修饰的方法,然后被绑定到静态的委托类型的字段
//声明委托:不带参
private delegate void DelegateMethod();
//声明委托:带参
private delegate void DelegateMethod2(int x, int y);
public void Test() { //1.0 1.1 DelegateMethod method = new DelegateMethod(CallMethod); //2.0 匿名方法 拷贝callMethod方法块,把 private void callMethod 换成 delegate DelegateMethod method2 = new DelegateMethod(delegate() { Console.Write("CallMethod被执行2"); }); //3.0 去掉delegate关键字,换成 在参数括号后面写 "=>"符号 DelegateMethod method3 = new DelegateMethod( () => { Console.Write("CallMethod被执行3"); }); //带参数形式 DelegateMethod2 method4 = new DelegateMethod2((int x, int y) => { Console.Write($"CallMethod被执行4 x:{x} y:{y}"); }); //省略参数类型 自动推算的 DelegateMethod2 method5 = new DelegateMethod2((x, y) => { Console.Write($"CallMethod被执行5 x:{x} y:{y}"); }); //如果方法体只有一行,省略大括号和分号 DelegateMethod2 method6 = new DelegateMethod2((x, y) => Console.Write($"CallMethod被执行6 x:{x} y:{y}")); //省略 new DelegateMethod2,编译器推算 DelegateMethod2 method7 = ((x, y) => Console.Write($"CallMethod被执行6 x:{x} y:{y}")); } //被委托回调的方法 private void CallMethod() { Console.Write("CallMethod被执行"); } private void CallMethod2(int x, int y) { Console.Write("CallMethod2被执行 x:" + x.ToString() + " y:" + y.ToString()); }
//为了防止滥用委托,微软后来定义了一个统一规范,那就是 Action(不带返回值)和Func(带返回值)
//就无需我们定义 private delegate void DelegateMethod(); 这样的形式的代码。
//可在使用的地方直接初始化委托,在接收委托的方法参数类型上进行统一
public void Test2()
{
Action method8 = () => Console.Write("这是无参无返回值委托初始化");
Action<int> method9 = (x) => Console.Write("这是有参无返回值委托初始化 x:" + x);
Func<int> method10 = () => 1; //这是无参带返回值int的委托
Func<int, string> method11 = (x) => x.ToString(); //这是有参带返回值string类型的委托
this.DoNothing(method8);
}
public void DoNothing(Action method)
{
}