C#语法之event关键字

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 事件访问器块。因此派生类必须提供其自己的实现。

posted @ 2008-06-30 22:43  superfang  阅读(1684)  评论(0编辑  收藏  举报