可以声名在类的外面 ,也可以是在类的内部
委托跟方法很像:也有返回值,有参数,用一个delegate关键字修饰;可以在类的内部声明,可以在类的外部声明
委托可以实例化 ,在实例化的时候需要传递一个方法进来
把方法当做参数的
在实例化的时候要求传递的方法结构和委托一直 :要求参数 和返回值一致
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public delegate void NoRunturnNoParameter();//没有返回值 没有形参 2 public delegate void NoRunturn(int x, int y);//没有返回值 有形参 3 public delegate int RunturnNoParameter();//没有返回值 没有形参 4 public delegate int Runturn(int x, int y);//没有返回值 有形参 5 public void show() 6 { 7 //委托可以实例化,在实例化的时候需要传递一个方法进来 8 NoRunturnNoParameter norunturn = new NoRunturnNoParameter(NoRunturnMethod); 9 norunturn.Invoke();//执行这个委托,== NoRunTurnMethod(); 10 // 在实例化的时候要求传递的方法结构和委托一直 :要求参数 和返回值一直 11 NoRunturn noRunturn = new NoRunturn(NoRunturnMethod); 12 noRunturn.Invoke(1, 2); 13 14 RunturnNoParameter runturnNoParameter = new RunturnNoParameter(RunturnIntMethod); 15 int ruslt1 = runturnNoParameter.Invoke(); 16 17 Runturn runturn = new Runturn(RunturnIntParameterMethod); 18 int ruslt2 = runturn.Invoke(1, 2); 19 } 20 public void NoRunturnMethod() 21 { 22 Console.WriteLine("这是一个无参数无返回值的方法!"); 23 } 24 public void NoRunturnMethod(int x, int y) 25 { 26 Console.WriteLine("这是一个有参数无返回值的方法!"); 27 } 28 public int RunturnIntMethod() 29 { 30 Console.WriteLine("这是一个有返回值 没有形参的方法"); 31 return 1; 32 } 33 public int RunturnIntParameterMethod(int x, int y) 34 { 35 Console.WriteLine("这是一个有返回值 有形参的方法"); 36 return x; 37 }
委托的实质 是什么
委托是一个类,继承了MulticastDeleGate特殊类
通过委托传递业务逻辑以后
-
增加公共业务逻辑方便,只需要一个方法内部增加即可,去掉了重复代码
-
如果新增业务逻辑 那么逻辑由调用者提供,做到了逻辑解耦
-
行为型设计模式,