Home >Backend Development >C#.Net Tutorial >Summarize the connection and difference between delegation and events
During interviews, we are often asked, what is the connection and difference between commissions and events? I have never fully understood it before, so I will summarize it below.
Start with an interesting requirement. There are three characters, the cat, the mouse and the owner. When the cat meows, the mouse starts to run away and the owner wakes up from his sleep.
The following code:
1 namespace ConsoleApplication4 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Cat cat = new Cat("猫"); 8 Mouse mouse1 = new Mouse("老鼠", cat); 9 Master master = new Master("张三", cat);10 //猫叫,通知所有订阅者11 cat.CatCry();12 13 Console.ReadKey();14 }15 }16 17 #region 猫18 public class Cat19 {20 private string name;21 22 //声明事件23 public event EventHandler<CatCryEventArgs> CatCryEvent;24 25 public Cat(string name)26 {27 this.name = name;28 }29 30 public void CatCry()31 {32 //声明事件参数33 CatCryEventArgs args = new CatCryEventArgs(name);34 Console.WriteLine(args);35 36 //触发事件37 CatCryEvent(this, args);38 }39 }40 41 /// <summary>42 /// 事件参数43 /// </summary>44 public class CatCryEventArgs : EventArgs45 {46 private string catName;47 48 public CatCryEventArgs(string catName)49 : base()50 {51 this.catName = catName;52 }53 54 public override string ToString()55 {56 return string.Format("{0}叫了", catName);57 }58 }59 #endregion60 61 #region 老鼠62 public class Mouse63 {64 private string name;65 public Mouse(string name, Cat cat)66 {67 this.name = name;68 cat.CatCryEvent += CatCryEventHandler;//本质上就是往委托链中添加一个方法69 }70 71 //事件处理程序72 private void CatCryEventHandler(object sender, CatCryEventArgs e)73 {74 Console.WriteLine("{0}逃走了:我勒个去,赶紧跑啊!", name);75 }76 }77 #endregion78 79 #region 主人80 public class Master81 {82 private string name;83 public Master(string name, Cat cat)84 {85 this.name = name;86 cat.CatCryEvent += CatCryEventHandler;//本质上就是往委托链中添加一个方法87 }88 89 //事件处理程序90 private void CatCryEventHandler(object sender, CatCryEventArgs e)91 {92 Console.WriteLine("{0}醒了:我勒个去,叫个锤子!", name);93 }94 }95 #endregion96 97 }
It can be summarized through demo:
1, The process of defining and using events is as shown below:
2. To define event parameters, you must inherit EventArgs. To define events, use public event EventHandler
3. The event uses the observer pattern, with publishing, subscription and notification. As for how to implement it, the essence will be summarized below.
1 namespace ConsoleApplication5 2 { 3 //声明委托 4 public delegate void Del1(); 5 6 class Program 7 { 8 static void Main(string[] args) 9 {10 //创建委托链(链式委托)11 Del1 del1 = () => Console.WriteLine("猫叫了");12 del1 += () => Console.WriteLine("老鼠逃走了:我勒个去,赶紧跑啊!");13 del1 += () => Console.WriteLine("主人醒了:我勒个去,叫个锤子!");14 15 //调用委托16 del1();17 18 Console.ReadKey();19 }20 21 }22 }
It can be seen that it is actually a chain delegation call. Three methods are added to the chain delegate, which are executed in sequence when called.
In order to fully understand the relationship between events and delegates, we look at the source code of EventHandler, as shown below.
See the red mark in the picture above? Therefore, events are implemented based on delegation. To summarize:
Contact:
1, events are implemented based on delegation, which can be understood popularly as: Events are a special kind of delegation, and the special thing is that It defines a delegate with two parameters (event source and event parameters) and no return value.
2, When a subscriber of an event subscribes to an event, it essentially adds the event processing method to the delegation chain, when When an event is triggered, all event handling methods in the delegation chain will be called.
Difference:
The essence of a delegate is a custom type (class), while the essence of an event is a special delegate instance (object) .
The above is the detailed content of Summarize the connection and difference between delegation and events. For more information, please follow other related articles on the PHP Chinese website!