event 關鍵字的來由,為了簡化自定義方法的構建來為委托調用列表增加和刪除方法。
在編譯器處理 event 關鍵字的時候,它會自動提供注冊和注銷方法以及任何必要的委托類型成員變量。
這些委托成員變量總是聲明為私有的,因此不能直接從觸發事件對象訪問它們。
溫馨提示:如果您對於委托不是很了解,您可以先看 C#委托(Delegate) ,這對您理解本章會有所幫助。
定義一個事件的步驟:
話不多說,我們來看一個示例:
1. 定義Car類:
public class Car { // 這個委托用來與Car事件協作 public delegate void CarEngineHandler(string msg);
// 這種汽車可以發送這些事件 public event CarEngineHandler Exploded; public event CarEngineHandler AboutToBlow; public int CurrentSpeed { get; set; } public int MaxSpeed { get; set; } public string PetName { get; set; } private bool CarIsDead; public Car() { MaxSpeed = 100; } public Car(string name, int maxSp, int currSp) { CurrentSpeed = currSp; MaxSpeed = maxSp; PetName = name; } public void Accelerate(int delta) { // 如果Car無法使用了,觸發Exploded事件 if (CarIsDead) { if (Exploded != null) { Exploded("sorry,this car is dead"); } } else { CurrentSpeed += delta; // 確認已無法使用,觸發AboutToBlow事件 if ((MaxSpeed - CurrentSpeed) == 10 && AboutToBlow != null) { AboutToBlow("careful buddy ! gonna blow !"); } if (CurrentSpeed >= MaxSpeed) { CarIsDead = true; } else { Console.WriteLine($"CurrentSpeed={CurrentSpeed}"); } } } }
以上我們已經設定了Car對象發送兩個自定義事件,這不再需要自定義注冊函數,也不需要聲明委托成員變量。稍後我們將說到如何使用這個汽車,在此之前,讓我們了解一下事件的架構,揭開事件的神秘面紗。
2. 事件神秘面紗
C#事件事實上會擴展兩個隱藏的公共方法,一個 add_事件名稱,一個 remove_事件名稱。
add_Exploded() CIL指令
remove_Exploded() CIL指令
代表事件本身的CIL代碼使用 .addon 和 .removeon 指令調用對應的 add_xxx() 和 remove_xxx()方法
3. 使用Car類
了解了這些之後,我們來使用之前定義的Car類:
public class MyEvent { public static void Show() { WriteLine("fun with events"); Car c1 = new Car("bwm", 100, 10); // 注冊事件處理程序 c1.AboutToBlow += new Car.CarEngineHandler(CarIsAlomostDoomed); c1.AboutToBlow += new Car.CarEngineHandler(CarAboutToBlow); Car.CarEngineHandler d = new Car.CarEngineHandler(CarExploded); c1.Exploded += d; WriteLine("******Speeding up******"); for (int i = 0; i < 6; i++) { c1.Accelerate(20); } // 注銷,從調用列表中移除CarExploded()方法 c1.Exploded -= d; WriteLine("******Speeding up******"); for (int i = 0; i < 6; i++) { c1.Accelerate(20); } } private static void CarExploded(string msg) => WriteLine($"CarExploded-> {msg}"); private static void CarAboutToBlow(string msg) => WriteLine($"CarAboutToBlow=>{msg}"); private static void CarIsAlomostDoomed(string msg) => WriteLine($"CarIsAlomostDoomed-> {msg}"); }
運行效果圖:
為了進一步簡化事件注冊,我們可以用到委托章節學習到的方法組轉換語法(解釋:我可以在調用以委托作為參數的方法時,直接提供方法的名稱,而不是委托對象)
下面請看使用方法組轉換,注冊和注銷事件,粗體部分:
public static void Show() { WriteLine("fun with events"); Car c1 = new Car("bwm", 100, 10); // 注冊事件處理程序 c1.AboutToBlow += CarIsAlomostDoomed; c1.AboutToBlow += CarAboutToBlow; c1.Exploded += CarExploded; WriteLine("******Speeding up******"); for (int i = 0; i < 6; i++) { c1.Accelerate(20); }
// 注銷,從調用列表中移除CarExploded()方法 c1.Exploded -= CarExploded; WriteLine("******Speeding up******"); for (int i = 0; i < 6; i++) { c1.Accelerate(20); } }
4. 創建自定義事件參數
微軟的事件模式:(System.Object sender,System.EventArgs args)這一兩個參數的模型。
第一個參數 sender :表示一個對發送事件的對象(Car)的引用,
第二個參數 args :與該事件相關的信息
System.EventArgs 基類源代碼:
public class EventArgs { public static readonly EventArgs Empty = new EventArgs(); public EventArgs() { } }
那麼對於簡單的事件類型來說,我們可以直接傳遞一個EventArgs的實例,但是如果我們期望傳遞自定義的數據,就應該從System.EventArgs派生出一個子類。
我們接下來就為我們的 Car 自定義一個符合這種事件模式的事件參數,新建一個 CarEventArgs 類,包含一個字符串,表示要發送給接收者的信息:
public class CarEventArgs : EventArgs { public readonly string msg; public CarEventArgs(string message) { msg = message; } }
我們修改一下Car類,新添加一個 CarCustomEngineHandler 委托,並且更改相應的事件代碼:
public class Car { public delegate void CarCustomEngineHandler(object sender, CarEventArgs e); // 模仿微軟正規(object sender, EventArgs e)寫法 public event CarCustomEngineHandler CustomExploded; public event CarCustomEngineHandler CustomAboutToBlow; public void AccelerateCustom(int delta) { if (CarIsDead) { if (CustomExploded != null) { CustomExploded(this, new CarEventArgs("sorry,this car is dead")); } } else { CurrentSpeed += delta; if ((MaxSpeed - CurrentSpeed) == 10 && CustomAboutToBlow != null) { CustomAboutToBlow(this, new CarEventArgs("careful buddy ! gonna blow !")); } if (CurrentSpeed >= MaxSpeed) { CarIsDead = true; } else { Console.WriteLine($"CurrentSpeed={CurrentSpeed}"); } } } }
看一下調用粗體部分(是如何使用傳遞的參數sender,e的):
public class MyCustomEvents { public static void Show() { WriteLine("fun with events"); Car c1 = new Car("bwm", 100, 10); c1.CustomAboutToBlow += CarIsAlomostDoomed; c1.CustomAboutToBlow += CarAboutToBlow; Car.CarCustomEngineHandler d = CarExploded; c1.CustomExploded += d; WriteLine("******Speeding up******"); for (int i = 0; i < 6; i++) { c1.AccelerateCustom(20); } c1.CustomExploded -= d; WriteLine("******Speeding up******"); for (int i = 0; i < 6; i++) { c1.AccelerateCustom(20); } } private static void CarExploded(object sender, CarEventArgs e) => WriteLine($"CarExploded->{((Car)sender)?.PetName} {e.msg}"); private static void CarAboutToBlow(object sender, CarEventArgs e) => WriteLine($"CarAboutToBlow=>{((Car)sender)?.PetName} {e.msg}"); private static void CarIsAlomostDoomed(object sender, CarEventArgs e) => WriteLine($"CarIsAlomostDoomed->{((Car)sender)?.PetName} {e.msg}"); }
5. 泛型 EventHandler<T> 委托
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);
由於很多自定義委托接受(object,EventArgs)這樣的參數結構,那麼我們可以使用框架內置的 EventHandler<> 來簡化我們的事件 委托。
首先修改一下Car類:
public class Car { public event EventHandler<CarEventArgs> StandardExploded; public event EventHandler<CarEventArgs> StandardAboutToBlow; public void AccelerateStandard(int delta) { if (CarIsDead) { if (StandardExploded != null) { StandardExploded(this, new CarEventArgs("sorry,this car is dead")); } } else { CurrentSpeed += delta; if ((MaxSpeed - CurrentSpeed) == 10 && StandardAboutToBlow != null) { StandardAboutToBlow(this, new CarEventArgs("careful buddy ! gonna blow !")); } if (CurrentSpeed >= MaxSpeed) { CarIsDead = true; } else { Console.WriteLine($"CurrentSpeed={CurrentSpeed}"); } } } }
調用代碼其實和上一段並沒有太大差異,這裡還是貼出來:
public class MyStandardEvent { public static void Show() { WriteLine("fun with events"); Car c1 = new Car("bwm", 100, 10); c1.StandardAboutToBlow += CarIsAlomostDoomed; c1.StandardAboutToBlow += CarAboutToBlow; EventHandler<CarEventArgs> d = CarExploded; c1.StandardExploded += d; WriteLine("******Speeding up******"); for (int i = 0; i < 6; i++) { c1.AccelerateStandard(20); } c1.StandardExploded -= d; WriteLine("******Speeding up******"); for (int i = 0; i < 6; i++) { c1.AccelerateStandard(20); } } private static void CarExploded(object sender, CarEventArgs e) => WriteLine($"CarExploded->{((Car)sender)?.PetName} {e.msg}"); private static void CarAboutToBlow(object sender, CarEventArgs e) => WriteLine($"CarAboutToBlow=>{((Car)sender)?.PetName} {e.msg}"); private static void CarIsAlomostDoomed(object sender, CarEventArgs e) => WriteLine($"CarIsAlomostDoomed->{((Car)sender)?.PetName} {e.msg}"); }
6.匿名方法
這麼簡單的處理操作, CarExploded() ,CarAboutToBlow()這一的方法很少會被調用委托之外的任何程序所調用。從生成效率來說,手工定義一個由委托對象調用的方法有點麻煩耶。
為了解決這種情況,現在事件注冊時,可以直接將一個委托與一段代碼關聯 -- 匿名方法。
我們修改一下調用Car類的地方(注意粗體部分、最後一個大括號 ";" 結束):
public class MyAnonymousMtehoden { public static void Show() { int aboutToBlowCounter = 0; WriteLine("fun with events"); Car c1 = new Car("bwm", 100, 10); c1.StandardAboutToBlow += delegate { WriteLine("Eek,going to fast"); }; c1.StandardAboutToBlow += delegate (object sender, CarEventArgs e) { aboutToBlowCounter++; WriteLine($"CarAboutToBlow=>{((Car)sender)?.PetName} {e.msg}"); }; c1.StandardExploded += delegate (object sender, CarEventArgs e) { aboutToBlowCounter++; WriteLine($"Exploded=>{((Car)sender)?.PetName} {e.msg}"); }; for (int i = 0; i < 6; i++) { c1.AccelerateStandard(20); } WriteLine($"aboutToBlowCounter={aboutToBlowCounter}"); } }
本文參考《精通C#》
學無止境,望各位看官多多指教。