每次用到委拖(代理)都有点晕,今天把汇总一下,方便后面回顾。
一 、delegate、 Action(Fun)
//委托是一个类型,继承自System.MulticastDelegate
声明委托
public delegate void NoReturnNoPara(); //无参无返回值
public delegate void NoReturnWithPara(string name);//有参无返回值
public delegate int WithReturnNoPara(); //无参有回值
public void Show()
{
//把方法包裹到变量里面去,变量invoke可以调用方法 把方法当成了一个变量
NoReturnNoPara method1 = new NoReturnNoPara(this.DoNothing);//2 委托实例化
method1.Invoke(); //3 委托实例的调用1
method1(); //3 委托实例的调用2
this.DoNothing();
NoReturnWithPara method2 = new NoReturnWithPara(this.DoNothingWithPara);
method2("hello");
}
private void DoNothing()
{
Console.WriteLine("这里是DoNothing");
}
private void DoNothingWithPara(string name)
{
Console.WriteLine(name);
}
private int ReturnStr(String name)
{ String newName ="名子:"+name;
return newName;
}
2 Action(无反返)、Fun(有返回)
Action 是将Delegate 的类型定义和实例化省去了,简化了代码(官方https://docs.microsoft.com/en-us/dotnet/api/system.action-1?redirectedfrom=MSDN&view=net-5.0)
上面的两个方法使用就简化了
public void Show()
{
Action method1= DoNothing; //无参数
method1();
Action<String> method2 =DoNothingWithPara;
method2("Hello");
Fun<String,String> method3 = returnStr;//带1个参数,返回值。
String newName= method3("liLei");
}
二、匿名方法、 Lambda
这两个是简化了 方法的定义。
3 匿名方法
public delegate void NoReturnNoPara(); //无参无返回值
public delegate void NoReturnWithPara(string name);//有参无返回值
public delegate int WithReturnNoPara(); //无参有回值
public void Show()
{
NoReturnNoPara method1 = delegate() {Console.WriteLine("这里是DoNothing");};
//DoNothing() 这个方法直接移到Show方法里面,DoNothing()方法相当于被隐藏了。
method1();
NoReturnWithPara method2 = delegate( name){Console.WriteLine(name);};
method2("Hello");
ReturnStr method3 =delegate(name){String newName ="名子:"+name;return newName;};
String newName= method3("lilei");
}
4 Lambda方法
public void Show()
{
NoReturnNoPara method1 =() =>Console.WriteLine("这里是DoNothing");
method1();
NoReturnWithPara method2 = ( name)=>Console.WriteLine(name);
method2("liLei");
ReturnStr method3=(name) =>{String newName ="名子:"+name;return newName;};
}
5,进一步简化 Action+lambda,简去委托定义和方法嵌入
public void Show()
{
Action method1 =() =>Console.WriteLine("这里是DoNothing");
method1();
Action method2 = ( name)=>Console.WriteLine(name);
method2();
Fun<String,String> method2 = ( name)=>{String newName ="名子:"+name;return newName;};
String newName=method2("liLei");
}
这么一理,还是比清楚了。