1、定義委託:委託是一個特殊的類,委託能夠將方法當成參數傳遞,委託的關鍵字是delegate。spa
2、委託三部曲日誌
1.聲明委託code
1 /// <summary> 2 /// 聲明沒有返回值且有一個參數爲String類型的委託 3 /// </summary> 4 /// <param name="name"></param> 5 public delegate void SayHiDelegate(string name);
2.實例化委託blog
1 SayHiDelegate sayHiDelegate = new SayHiDelegate(SayHiChinese); //2.委託實例化 string
3.調用委託,而且傳參數it
1 //3.調用委託 2 var name = "劉輝華"; 3 SayHiMethodDelegate(name, sayHiDelegate);
3、爲何要用委託。寫到這裏咱們先看個下面一個問題:io
模擬場景:1.一箇中國打招呼說:您好 2.如今來了個美國人打招呼說:hi 3.若是再來個法國人,日本人.... class
那麼有的人就開始說了,能夠用IF判斷呀。說的沒錯,代碼以下:方法
1 public static void SayHiChinese(string name) 2 { 3 //記錄日誌(重複代碼) 4 Console.WriteLine("記錄日誌功能"); 5 Console.WriteLine($"{name}說:你好"); 6 } 7 8 public static void SayHiAmerican(string name) 9 { 10 //記錄日誌(重複代碼) 11 Console.WriteLine("記錄日誌功能"); 12 Console.WriteLine($"{name}說:hi"); 13 } 14 15 public static void SayHi(string name, Language language) 16 { 17 switch (language) 18 { 19 case Language.Chinese: 20 SayHiChinese(name); 21 break; 22 case Language.American: 23 SayHiAmerican(name); 24 break; 25 default: 26 throw new Exception("沒有這個國家的人中"); 27 } 28 }
1 System.Console.WriteLine("IF 判斷"); 2 //實例化委託 3 SayHiDelegate sayHiChinese = new SayHiDelegate(People.SayHiChinese); 4 //調用委託 5 string name = "小強"; 6 sayHiChinese.Invoke(name); 7 8 //實例化委託 9 SayHiDelegate syHiAmerican = new SayHiDelegate(People.SayHiAmerican); 10 //調用委託 11 string nameEn = "Json"; 12 syHiAmerican.Invoke(nameEn);
我這裏只寫了兩個國家的人說兩種語言,那麼若是我在加一個國家的人說的語言勢必會更改方法,這樣就違背了開閉原則。若是要在每一個國家的SayHi方法裏面加入日誌的話,兩個國家的SayHi方法裏面就會有重複的代碼。
下面咱們用最完美的委託來解決這些問題,其實很簡單:static
/// <summary> /// 委託方法 /// </summary> /// <param name="name"></param> /// <param name="sayHi"></param> public static void SayHiCommonMethod(string name, SayHiDelegate sayHi) { //記錄日誌(重複代碼) Console.WriteLine("記錄日誌功能"); sayHi.Invoke(name); } //調用委託 string nameEn = "Json"; //調用委託 string name = "小強"; People.SayHiCommonMethod(name, People.SayHiChinese); People.SayHiCommonMethod(nameEn, People.SayHiAmerican);