摘自http://www.cnblogs.com/willick/p/4172174.html,僅供參考學習
.NET框架為事件編程定義了一個標准模式,設定這個標准是為了讓.NET框架和用戶代碼保持一致。System.EventArgs是標准模式的核心,它是一個沒有任何成員,用於傳遞事件參數的基類,首先定義EventArgs:
1 public class PriceChangeEventArgs : System.EventArgs {
2 public readonly decimal oldPrice;
3 public readonly decimal newPrice;
4 public PriceChangeEventArgs(decimal oldPrice, decimal newPrice) {
5
6 this.oldPrice = oldPrice;
7 this.newPrice = newPrice;
8 }
9 }
然後為事件定義委托,必須滿足以下條件:
由於考慮到每個事件都要定義自己的委托很麻煩,.NET 框架為我們預定義好一個通用委托System.EventHandler<TEventArgs>:
public delegate void EventHandler<TEventArgs> (object source, TEventArgs e) where TEventArgs : EventArgs;
如果不使用框架的EventHandler<TEventArgs>,我們需要自己定義一個:
public delegate void PriceChangedEventHandler (object sender, PriceChangedEventArgs e);
如果不需要參數,可以直接使用EventHandler(不需要<TEventArgs>)。有了EventHandler<TEventArgs>,我們就可以這樣定義示例中的事件:
public class IPhone6 {
...
public event EventHandler<PriceChangedEventArgs> PriceChanged;
...
}
最後,事件標准模式還需要寫一個受保護的虛方法來觸發事件,這個方法必須以On為前綴,加上事件名(PriceChanged),還要接受一個EventArgs參數,如下:
1 public class IPhone6 {
2 ...
3 public event EventHandler<PriceChangedEventArgs> PriceChanged;
4 protected virtual void OnPriceChanged(PriceChangedEventArgs e) {
5 if (PriceChanged != null) PriceChanged(this, e);
6 }
7 ...
8 }
下面給出完整示例:
public class PriceChangedEventArgs : System.EventArgs {
public readonly decimal OldPrice;
public readonly decimal NewPrice;
public PriceChangedEventArgs(decimal oldPrice, decimal newPrice) {
OldPrice = oldPrice;
NewPrice = newPrice;
}
}
public class IPhone6 {
decimal price;
public event EventHandler<PriceChangedEventArgs> PriceChanged;
protected virtual void OnPriceChanged(PriceChangedEventArgs e) {
if (PriceChanged != null) PriceChanged(this, e);
}
public decimal Price {
get { return price; }
set {
if (price == value) return;
decimal oldPrice = price;
price = value;
// 如果調用列表不為空,則觸發。
if (PriceChanged != null)
OnPriceChanged(new PriceChangedEventArgs(oldPrice, price));
}
}
}
class Program {
static void Main() {
IPhone6 iphone6 = new IPhone6() { Price = 5288M };
// 訂閱事件
iphone6.PriceChanged +=iphone6_PriceChanged;
// 調整價格(事件發生)
iphone6.Price = 3999;
Console.ReadKey();
}
static void iphone6_PriceChanged(object sender, PriceChangedEventArgs e) {
Console.WriteLine("年終大促銷,iPhone 6 只賣 " + e.NewPrice + " 元, 原價 " + e.OldPrice + " 元,快來搶!");
}
}