C#——关键字:event

C#——关键字:event

event 关键字用于声明发布服务器类中的事件。

示例

下面的示例演示如何声明和引发使用 EventHandler 作为基础委托类型的事件。

public class SampleEventArgs
{
    public SampleEventArgs(string text) { Text = text; }
    public string Text { get; } // readonly
}

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 in a thread-safe manner using the ?. operator.
        SampleEvent?.Invoke(this, new SampleEventArgs("Hello"));
    }
}

事件是一种特殊的多播委托,仅可以从声明事件的类或结构(发布服务器类)中对其进行调用。 如果其他类或结构订阅该事件,则在发布服务器类引发该事件时,将调用其事件处理程序方法。

可以将事件标记为public、private、protected、internal、protected internal 或 private protected。 这些访问修饰符定义该类的用户访问该事件的方式。

关键字和事件

下列关键字应用于事件。

关键字	                 说明	                        更多信息
static	使事件可供调用方在任何时候进行调用,即使不存在类的实例。	静态类和静态类成员 

virtual	允许派生类使用重写关键字重写事件行为。	            继承

 sealed	指定对于派生类,它不再是虚拟的。	

abstract 编译器不会生成 add 和 remove 事件访问器块,因此派生类必须提供其自己的实现。

可以通过使用静态关键字将事件声明为静态事件。 这可使事件可供调用方在任何时候进行调用,即使不存在类的实例。

可以通过使用虚拟关键字将事件标记为虚事件。 这可使派生类使用重写关键字重写事件行为。重写虚拟事件的事件也可以为密封,指定对于派生类,它不再是虚拟的。 最后,可以声明事件为抽象,这意味着编译器将不会生成 add 和 remove 事件访问器块。 因此,派生类必须提供其自己的实现。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值