委托之初识(一)
一、委托:也是一個類,繼承自System.MulticastDelegate。可以理解為:A想找個女朋友(C),B是婚介所,A委托B幫忙能找到C。
?
二、示例:
1 //定義一個帶有參數的委托,委托的參數類型要跟AppleCompany類中的四個方法保持一致,都是Int32類型,委托其實就是個類,一般為了調用方便都聲明在命名空間Delegate_01中. 2 public delegate void Dele(Int32 num); 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 DigitalFactory df = new DigitalFactory(); 8 df.MakeDigitals(AppleCompany.MakeIphone, 200); 9 df.MakeDigitals(new AppleCompany().MakeIpad, 200); 10 df.MakeDigitals(new AppleCompany().MakeImac, 200); 11 df.MakeDigitals(new AppleCompany().MakeIpod, 200); 12 } 13 } 14 15 //在DigitalFactory創建一個帶有委托參數的方法,用來傳遞方法,然后通過委托調用具體方法 16 public class DigitalFactory 17 { 18 public void MakeDigitals(Dele dele, Int32 Number) 19 { 20 if (dele != null) 21 { 22 dele(Number); 23 Console.WriteLine("Target:" + dele.Target + ",Method:" + dele.Method.Name); 24 } 25 } 26 } 27 28 //在AppleCompany類,有個四個方法。 29 public class AppleCompany 30 { 31 public static void MakeIphone(int num) 32 { 33 Console.WriteLine(num + "臺Iphone 已生產出來"); 34 } 35 36 public void MakeIpad(int num) 37 { 38 Console.WriteLine(num + "臺Ipad 已生產出來"); 39 } 40 41 public void MakeImac(int num) 42 { 43 Console.WriteLine(num + "臺Imac 已生產出來"); 44 } 45 46 public void MakeIpod(int num) 47 { 48 Console.WriteLine(num + "臺Ipod 已生產出來"); 49 Console.Read(); 50 } 51 } View Code結果:
?
三、綁定多個方法
1 static void Main(string[] args) 2 { 3 DigitalFactory df = new DigitalFactory(); 4 //委托綁定多個方法。 5 Dele deles = new Dele(AppleCompany.MakeIphone); 6 deles += new AppleCompany().MakeIpad; 7 deles += new AppleCompany().MakeImac; 8 deles += new AppleCompany().MakeIpod; 9 df.MakeDigitals(deles,200); 10 } View Code結果:
?
?
? ?下載源代碼
?
?
?
轉載于:https://www.cnblogs.com/luyuwei/p/3628778.html
總結
- 上一篇: CMD下查询Mysql中文乱码的解决方法
- 下一篇: 基于Flask开发企业级REST API