EventHandler<TEventArgs>的定義如下
public delegate void EventHandler<TEventArgs>(object sender,TEventArgs e) where TEventArgs:EventArgs
第一個參數必須是object類型(是一個對象,包含事件的發送者)
第二個參數是T類型(即泛型),定義了一個T的約束,它必須派生自基類EventArgs
CardInfoEventArgs 就派生自基類EventArgs
-----------舉例---------------
#region 測試事件1
//EventArgs類
public class CardInfoEventArgs : EventArgs
{
public string Car { get; private set; }
public CardInfoEventArgs(string car)
{
this.Car = car;
}
}
//觸發事件的類
public class CarDealer
{
public event EventHandler<CardInfoEventArgs> NewCardInfo;
public void NewCar(string car)
{
Console.WriteLine("CarDealer,new car{0}", car);
//在觸發事件之前,需要檢查委托NewCardInfo是否不為空。如果沒有訂閱處理程序,委托就是空
if (NewCardInfo != null)
{
NewCardInfo(this, new CardInfoEventArgs(car));
}
}
}
//處理事件的類
public class Consumer
{
private string name;
public Consumer(string name)
{
this.name = name;
}
//處理事件的方法
public void NewCarIsHere(object sender, CardInfoEventArgs e)
{
Console.WriteLine("{0}:car {1} is new", name, e.Car);
}
}
#endregion
private void button_測試事件1_Click(object sender, EventArgs e)
{
CarDealer dealer = new CarDealer();
Consumer michael = new Consumer("Michael");
dealer.NewCardInfo += michael.NewCarIsHere; //訂閱事件
dealer.NewCar("寶馬");
Consumer nick = new Consumer("Nick");
dealer.NewCardInfo += nick.NewCarIsHere; //訂閱事件
dealer.NewCar("奔馳");
dealer.NewCardInfo -= michael.NewCarIsHere; //取消訂閱事件
dealer.NewCar("奧迪");
}
-----測試結果截圖-------