在.net 的世界里,離不開委托和事件,其實理解透了後很簡單,總結了一下分為6步: 1)定義委托 public delegate void RevicedEventHandler(object sender,RevicedEventArgs e); RevicedEventArgs :自定義參數源, ...
在.net 的世界里,離不開委托和事件,其實理解透了後很簡單,總結了一下分為6步: 6)調用事件,滿足特定條件去調用 其實:.net 後續又提供了泛型版本委托:public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);
1 /// <summary> 2 /// 發佈者(中介) 3 /// </summary> 4 public class Publisher 5 { 6 7 8 public delegate void FindedSmallHouseEventHandler(object sender, HouseEventArgs e);//定義找小房子的委托 9 10 11 /// <summary> 12 /// 定義找小房子事件 13 /// </summary> 14 public event FindedSmallHouseEventHandler FindedSmallHouseEvent; 15 16 /// <summary> 17 /// (對內)定義觸發事件的函數 18 /// </summary> 19 /// <param name="e"></param> 20 protected virtual void OnFindedSmallHouse(HouseEventArgs e) 21 { 22 if (null != FindedSmallHouseEvent) 23 { 24 if (e.HouseType == HouseType.Small)//如果是小戶型,才會觸發事件,本人是屌絲,哈哈 25 { 26 FindedSmallHouseEvent(this, e); 27 } 28 29 } 30 } 31 32 /// <summary> 33 /// 對外部類公開觸發事件的函數 34 /// </summary> 35 public void StartFindHouse(HouseEventArgs e) 36 { 37 OnFindedSmallHouse(e); 38 } 39 }
1 /// <summary> 2 /// 訂閱者(我自己) 3 /// </summary> 4 public class Subscriber 5 { 6 7 public Subscriber(Publisher p) 8 { 9 p.FindedSmallHouseEvent += new FindedSmallHouseEventHandler(ReceivedSmallHouse); 10 11 } 12 13 14 15 /// <summary> 16 /// 定義找到小房子的事件處理程式(接受小房子) 17 /// </summary> 18 /// <param name="sender"></param> 19 /// <param name="e"></param> 20 public void ReceivedSmallHouse(object sender, HouseEventArgs e) 21 { 22 Console.WriteLine("我終於有房子了,再也不用流落街頭了。"); 23 Console.ReadKey(); 24 } 25 }
調用:
1 class Program 2 { 3 /// <summary> 4 /// 按滿足指定條件去調用事件(此場景就好比中介不停在找房子) 5 /// </summary> 6 /// <param name="args"></param> 7 static void Main(string[] args) 8 { 9 10 11 Publisher pub = new Publisher();//中介實例 12 Subscriber sb = new Subscriber(pub);//我自己 13 14 int i = int.MinValue; 15 bool f = true; 16 while (f) 17 { 18 Console.WriteLine("請輸入您要找的房型!"); 19 20 if (int.TryParse(Console.ReadLine().ToString(), out i)) 21 { 22 if (0 <= i && i <= 2) //定義了3種房型(小、一般、大戶型) 23 { 24 HouseEventArgs eg = new HouseEventArgs((HouseType)i); 25 pub.StartFindHouse(eg); //中介開始找房子 26 } 27 28 29 } 30 31 32 } 33 34 } 35 36 }
運行結果:
例子寫完了,有不好的地方歡迎指出!!!