委托、Lambda表达式、事件系列07,使用EventHandler委托
談到事件注冊,EventHandler是最常用的。
EventHandler是一個委托,接收2個形參。sender是指事件的發起者,e代表事件參數。
?
□ 使用EventHandler實現猜拳游戲
?
使用EventHandler實現一個猜拳游戲,每次出拳,出剪刀、石頭、布這三者的其中一種。
?
首先抽象出一個被觀察者,其中提供了事件,提供了執行事件的方法。
public class FistGame { public string FistName { get; set; } public event EventHandler GuessFist; public void Start() { if (GuessFist != null) { GuessFist(this, EventArgs.Empty); } } }
以上,在Start方法內部調用事件GuessFist的時候,實參this代表FistGame類本身。??
客戶端必須有一個方法和EventHandler的定義保持一致,這樣才可以注冊到FistGame類的EventHandler事件上。
class Program { static void Main(string[] args) { FistGame jiandao = new FistGame(){FistName = "剪刀"}; jiandao.GuessFist += GetFistResult; FistGame shitou = new FistGame() { FistName = "石頭" }; shitou.GuessFist += GetFistResult; FistGame bu = new FistGame() { FistName = "布" }; bu.GuessFist += GetFistResult; FistGame finalFist = null; var temp = new Random().Next()%3; if (temp == 0) { finalFist = jiandao; } else if(temp == 1) { finalFist = shitou; } else { finalFist = bu; } finalFist.Start(); } static void GetFistResult(object sender, EventArgs e) { FistGame fistGame = sender as FistGame; Console.WriteLine("本次出的拳為:" + fistGame.FistName); } }??
以上,GetFistResult方法的參數列表符合EventHandler的定義,并且給每個FistGame實例的GuessFist事件注冊了該方法。最后,根據隨機數來決定采用哪個FistGame實例。??
?
□ 使用EventHandler傳遞事件參數
?
首先需要一個派生于EventArgs的類,通過構造函數注入一個枚舉狀態。
public class FistGameEventArgs : EventArgs { public FistEnum CurrentFist { get; private set; } public FistGameEventArgs(FistEnum currentFist) { CurrentFist = currentFist; } } public enum FistEnum { jiandao, shitou, bu }?
作為被觀察者的FistGame來講,現在需要EventHandler<TEventArgs>泛型來實現。
public class FistGame { public string FistName { get; set; } public event EventHandler<FistGameEventArgs> GuessFist; public void Start() { if (GuessFist != null) { GuessFist(this, new FistGameEventArgs(FistEnum.jiandao)); } } }?
客戶端,與EventHandler參數列表一致的GetFistResult方法把事件參數顯示出來。???
static void Main(string[] args) { FistGame jiandao = new FistGame(){FistName = "剪刀"}; jiandao.GuessFist += GetFistResult; jiandao.Start(); } static void GetFistResult(object sender, FistGameEventArgs e) { FistGame fistGame = sender as FistGame; Console.WriteLine("從Name屬性獲得,本次出的拳為:" + fistGame.FistName); switch (e.CurrentFist) { case FistEnum.jiandao: Console.WriteLine("從事件參數獲得,本次出的拳為:剪刀"); break; case FistEnum.shitou: Console.WriteLine("從事件參數獲得,本次出的拳為:石頭"); break; case FistEnum.bu: Console.WriteLine("從事件參數獲得,本次出的拳為:布"); break; } } }?
總結:使用EventHandler委托不僅可以實現事件注冊和取消,而且還可以獲取事件發起者和事件參數。
?
?
“委托、Lambda表達式、事件系列”包括:
委托、Lambda表達式、事件系列01,委托是什么,委托的基本用法,委托的Method和Target屬性
委托、Lambda表達式、事件系列02,什么時候該用委托
委托、Lambda表達式、事件系列03,從委托到Lamda表達式
委托、Lambda表達式、事件系列04,委托鏈是怎樣形成的, 多播委托, 調用委托鏈方法,委托鏈異常處理
委托、Lambda表達式、事件系列05,Action委托與閉包
委托、Lambda表達式、事件系列06,使用Action實現觀察者模式,體驗委托和事件的區別
委托、Lambda表達式、事件系列07,使用EventHandler委托
轉載于:https://www.cnblogs.com/darrenji/p/4004343.html
總結
以上是生活随笔為你收集整理的委托、Lambda表达式、事件系列07,使用EventHandler委托的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面向关系数据库的智能索引调优方法
- 下一篇: 小白学JAVA,与你们感同身受,JAVA