C#文法之event關鍵字

來源:互聯網
上載者:User

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 事件訪問器塊。因此衍生類別必須提供其自己的實現。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.