一、定義
事件是兩個對象間發布消息和響應后處理消息的過程,通過委托類型來實現的。
事件的機制被稱為發布-訂閱機制,其算法過程為:首先定義一個委托類型,然后在發布者類中聲明一個event事件,同時此類中還有一個用來觸發事件的的方法,通過此方法來關聯事件。聲明訂閱者類,其中定義一個被調用方法,最后在主函數中完成事件的關聯和對方法的調用。
二、示例
1. 無參委托類型
舉個簡單的例子,我委托女朋友給我買東西,那我需要定義一個發布者類Me和一個訂閱者類Girlfriend。🐶
public class Me//發布者是我,hehe{public delegate void Buyfoodforme();//定義委托類型private int a;public event Buyfoodforme Buy;//基于委托類型定義事件public void Linkevent(){if (Buy != null){Buy();}else{Console.WriteLine("回來吧,我不想買了");Console.ReadKey();//按回車繼續}}public Me() //定義構造函數,單純試驗下{int a = 6;GetState(a);}public void GetState(int b){if (a != b){a = b;Linkevent();}}}public class Girlfriend//訂閱者。。{public void Runtobuy(){Console.WriteLine("我要趕緊跑步去買,嘻嘻");Console.ReadKey();}}
在主函數中關聯事件
public class Program{public static void Main(){Me me = new Me();//創建對象,同時調用構造函數Me,輸出"回來吧,我不想買了"Girlfriend gf = new Girlfriend();me.Buy += new Me.Buyfoodforme(gf.Runtobuy);//關聯被調用事件me.GetState(1);}}
2. 有參委托類型
using System;namespace Event1
{public delegate int NumManipulationHandler(int a, int b);//發布者類public class EventTest{//聲明事件public event NumManipulationHandler Numevent;int a = 1;int b = 1;//觸發事件的函數public void OnNumChanged(){Numevent?.Invoke(a, b);//空檢查運算符 }}//訂閱者類public class Suber{public int Sum(int a, int b){Console.WriteLine("Subscriber the changed number is {0}", a + b);return a + b;}public int Sub(int a, int b){Console.WriteLine("Subscriber the changed number is {0}", a - b);return a - b;}}class Program{static void Main(string[] args){EventTest e = new EventTest();Suber s = new Suber();e.Numevent += s.Sum;//注冊方法e.Numevent += s.Sub;e.OnNumChanged();//觸發事件}}
}
定義一個事件有兩步,首先定義一個委托,它包括了這件事的“協議”和委托方法(由誰去做);其次,用event關鍵字和相關委托聲明這個事件。事件像是一個接口,封裝了委托所定的“協議”。由于委托已經定義了協議,剩下的就是按這個協議去辦事,至于怎么做它并不關心。