談到事件注冊,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{
新聞熱點
疑難解答