事件:事件是委託的安全包裹,讓委託更加安全 是一種特色的變數型別
事件只能用+= -=來,而委託還可以用= 或者new來賦值
委託:以方法形式呼叫 ; 也可以+=,-=形式呼叫
1 2 //以方法引數形式呼叫 3 4 SayHello("小紅", chinesehHello); 5 6 7 //以+=, -=方式呼叫 8 9 HelloDelegate helloDelegate = new HelloDelegate(chinesehHello); 10 helloDelegate += englishHello; 11 SayHello("wenyu", helloDelegate); 12 13 helloDelegate -= englishHello; 14 SayHello("wenyu2", helloDelegate); 15 16 17 //================== 18 19 public delegate void HelloDelegate(string name); 20 21 public void SayHello(string name, HelloDelegate helloDelegate) 22 { 23 helloDelegate(name); 24 } 25 26 public void englishHello(string name) 27 { 28 helloList.Add($"hello,{name}"); 29 Console.WriteLine($"hello,{name}"); 30 } 31 public void chinesehHello(string name) 32 { 33 helloList.Add($"你好,{name}"); 34 35 Console.WriteLine($"你好,{name}"); 36 }
//事件:事件是委託的安全包裹,讓委託更加安全 是一種特色的變數型別
//事件只能用+= -=來,而委託還可以用= 或者new來賦值
1 Publisher publisher = new Publisher(); 2 Subscriber subscriber = new Subscriber(); 3 4 //事件:事件是委託的安全包裹,讓委託更加安全 是一種特色的變數型別 5 //事件只能用+= -=來,而委託還可以用= 或者new來賦值 6 7 publisher.addEvent += subscriber.addEmployee; 8 publisher.addEvent += subscriber.deleteEmployee; 9 //publisher.addEvent("");//不能直接使用 × 10 var result1 = publisher.executeEvent("我是event呼叫的"); //事件只能在宣告的類裡面呼叫 11 12 13 14 publisher.addDelegate += subscriber.addEmployee; 15 publisher.addDelegate += subscriber.deleteEmployee; 16 17 //會呼叫add,delete方法,但是返回只返回最後一個方法的返回值 18 var result2 = publisher.addDelegate("我是delegate呼叫的"); 19 20 21 22 //========================== 23 24 25 public delegate string MyDelegate(string msg); 26 public class Publisher 27 { 28 //事件作為成員變數存在於類中 ; 事件不能在類外面賦值+= -= ;事件不能在類外面出發呼叫 29 public event MyDelegate addEvent; 30 public MyDelegate addDelegate; 31 public string executeEvent(string msg) 32 { 33 //addEvent?.Invoke(msg); 34 return addEvent(msg); 35 } 36 } 37 public class Subscriber 38 { 39 public string addEmployee(string msg) 40 { 41 return $"addEmployee:{msg}"; 42 } 43 public string deleteEmployee(string msg) 44 { 45 return $"deleteEmployee:{msg}"; 46 } 47 }