事件:事件是委托的安全包裹,让委托更加安全 是一种特色的变量类型
事件只能用+= -=来,而委托还可以用= 或者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 }
标签:publisher,string,委托,c#,事件,msg,public,name From: https://www.cnblogs.com/hanliping/p/18367568