event 關鍵字用於在發行者類中聲明事件。

下面的示例演示如何聲明和引發將 EventHandler 用作基礎委託類型的事件。

public class Publisher{// Declare the delegate (if using non-generic pattern).public delegate void SampleEventHandler(object sender, SampleEventArgs e);// Declare the event.public event SampleEventHandler SampleEvent;// Wrap the event in a protected virtual method// to enable derived classes to raise the event.protected virtual void RaiseSampleEvent(){// Raise the event by using the () operator.SampleEvent(this, new SampleEventArgs("Hello"));}}

事件是特殊類型的多路廣播委託,僅可從聲明它們的類或結構(發行者類)中調用。如果其他類或結構訂閲了該事件,則當發行者類引發該事件時,會調用其事件處理程序方法。

事件可標記為 public、private、protected、internal 或 protected internal。這些訪問修飾符定義類的用户訪問事件的方式。

下面的關鍵字可應用於事件。

 

 

關鍵字

説明

static

即使類沒有實例,調用方也能在任何時候使用該事件。

virtual

允許派生類通過使用 override 關鍵字來重寫事件行為。

sealed

指定對於派生類它不再屬虛擬性質。

abstract

編譯器不會生成 add 和 remove 事件訪問器塊,因此派生類必須提供自己的實現。

 

通過使用 static 關鍵字,可以將事件聲明為靜態事件。即使類沒有任何實例,調用方也能在任何時候使用靜態事件。通過使用 virtual 關鍵字,可以將事件標記為虛擬事件。這樣,派生類就可以通過使用 override 關鍵字來重寫事件行為。重寫虛事件的事件也可以為 sealed,以表示其對於派生類不再是虛事件。最後,可以將事件聲明為 abstract,這意味着編譯器不會生成 add 和 remove 事件訪問器塊。因此派生類必須提供其自己的實現。