對於C#中的事件,我舉了個簡單的例子來理解事件及其處理。
這個例子中母親是事件的發布者,事件是吃飯了。兒子和父親是事件的訂閱者,各自的Eat方法是處理事件的方法。
下面是詳細的加注的例子:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.IO; 7 8 9 /* C#中處理事件采用發布-訂閱模型(publisher-subscriber model) 10 * 包含委托和事件申明的類是發布器 11 * 包含事件處理的類是訂閱器 12 * 13 * C#中申明事件以及事件處理的步驟: 14 * 1.定義委托和其相關聯的事件 15 * 2.在發布器中寫觸發事件的條件(方法、其他事件等) 16 * 3.在訂閱器中寫處理事件的方法程序 17 * 4.將事件訂閱處理事件的程序,格式是: <事件> += new <與事件關聯的委托>( <處理事件的方法名> ) 18 */ 19 namespace CsharpStudy 20 { 21 //定義一個“母親”類,是發布器 22 class Mum { 23 //與事件關聯的委托的定義 24 public delegate void mydelegate(); 25 //事件的定義 26 public event mydelegate EatEvent; 27 28 public void Cook() { 29 Console.WriteLine("母親:我飯做好了,快來吃飯了..."); 30 //觸發事件 31 EatEvent(); 32 } 33 34 } 35 36 //定義一個“兒子”類,是訂閱器 37 class Son { 38 //事件處理方法 39 public void Eat() { 40 Console.WriteLine("兒子:好,等會,媽,我玩完這局再吃..."); 41 } 42 } 43 44 //定義一個“父親”類,是訂閱器 45 class Father { 46 //事件處理方法 47 public void Eat() { 48 Console.WriteLine("父親:好,老婆,我來吃飯了..."); 49 } 50 } 51 52 53 //主程序類 54 class Program 55 { 56 //程序入口 57 static void Main(string[] args) 58 { 59 /************Main function***************/ 60 //實例化三個類 61 Mum mun = new Mum(); 62 Father father = new Father(); 63 Son son = new Son(); 64 65 //事件訂閱方法(訂閱son和father的Eat方法) 66 mun.EatEvent += new Mum.mydelegate(son.Eat); 67 mun.EatEvent += new Mum.mydelegate(father.Eat); 68 69 mun.Cook(); 70 71 72 /****************************************/ 73 74 Console.ReadKey(); 75 } 76 } 77 78 79 }
雖然這個例子比較簡單,但是能夠最粗糙的對事件的發布-訂閱模型有個最直觀的理解。