標籤:stat code col 實現 event 傳遞 www. color 註冊
我們用一個簡單的例子,來說明一下這種訊息傳遞的機制。
有一家三口,媽媽負責做飯,爸爸和孩子負責吃。。。將這三個人,想象成三個類。
媽媽有一個方法,叫做“做飯”。有一個事件,叫做“開飯”。做完飯後,調用開發事件,發布開飯訊息。
爸爸和孩子分別有一個方法,叫做“吃飯”。
將爸爸和孩子的“吃飯”方法,註冊到媽媽的“開飯”事件。也就是,訂閱媽媽的開飯訊息。讓媽媽做完飯開飯時,發布吃飯訊息時,告訴爸爸和孩子一聲。
這種機制就是C#中的,訂閱發布。下面我們用代碼實現:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace EventSimpleDemo 7 { 8 class Program 9 {10 static void Main(string[] args)11 {12 Mom mom = new Mom();13 Dad dad = new Dad();14 Son son = new Son();15 mom.Eat += new Action(dad.Eat);// 訂閱16 //mom.Eat += new Action(son.Eat);17 18 mom.Cooking();19 Console.ReadKey();20 }21 }22 23 public class Mom24 {25 //public delegate void delegateAction();26 public event Action Eat;// Action 可以改成委託方法:delegateAction27 28 public void Cooking()29 {30 Console.WriteLine("媽媽:飯好了!");31 if (Eat != null)32 {33 Eat();34 }35 } 36 }37 38 public class Dad39 {40 public void Eat()41 {42 Console.WriteLine("爸爸:馬上來!");43 }44 }45 46 public class Son47 {48 public void Eat()49 {50 Console.WriteLine("兒子:等會再吃!");51 }52 }53 54 }
來源:http://www.cnblogs.com/David-Huang/p/5150671.html
作者寫的這個事件通俗易懂,忍不住把它拷貝過來
C# Event事件的訂閱與發布