1、.NetFramework1.0 1.1
//声明委托
public delegate void NoReturnNoPara();
//给委托赋值
NoReturnNoPara method = new NoReturnNoPara(this.DoNothing);
//执行委托
method.Invoke();
//方法
private void DoNothing()
{
Console.WriteLine("***这是方法***:什么也不做");
}
2、.NetFramework2.0 有了匿名方法、delegate关键字
//同样的效果,比1.0更简洁了
NoReturnWithPara method = new NoReturnWithPara(delegate (int id, string name)
{
Console.WriteLine($"***这是方法***:匿名方法:{id} {name}");
});
method.Invoke(20200316, "2020年3月16日17:02:23");
3、.NetFramework3.0 把delegate关键字去掉,增加了一个箭头goes to 也就是:=>
NoReturnWithPara method = new NoReturnWithPara((int id, string name) =>
{
Console.WriteLine($"***这是方法***:{id} {name}");
});
method.Invoke(20200316, "2020年3月16日17:06:31");
4、可以省略参数类型,编译器的语法糖,虽然没写,编译时还是有的,根据委托推算
NoReturnWithPara method = new NoReturnWithPara((id, name) =>
{
Console.WriteLine($"{id} {name}");
});
method.Invoke(20200316, "2020年3月16日17:13:11");
5、如果方法体只有一行,可以去掉大括号和分号,new NoReturnWithPara也可以省掉,也是语法糖,编译器自动加上
NoReturnWithPara method = (id, name) => Console.WriteLine($"{id} {name}");
method.Invoke(123, "2020年3月17日12:12:35");
6、也可以把声明的委托省掉,直接用Action和Func
Func<int, int, int> funcB = (a, b) => a + b;
int d = funcB.Invoke(10,30);
Console.WriteLine($"FuncB返回值:{d}");
可以看出来lambda就是委托