C# Event事件的訂閱與發布

來源:互聯網
上載者:User

標籤: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事件的訂閱與發布

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.