• event 关键字


    event(C# 参考)

    event 关键字用于在发行者类中声明事件。
    下面的示例演示如何声明和引发将 EventHandler 用作基础委托类型的事件。

    C#
    
    public class SampleEventArgs
    {
        public SampleEventArgs(string s) { Text = s; }
        public String Text {get; private set;} // 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 by using the () operator.
            if (SampleEvent != null)
                SampleEvent(this, new SampleEventArgs("Hello"));
        }
    }

    事件是特殊类型的多路广播委托,仅可从声明它们的类或结构(发行者类)中调用。如果其他类或结构订阅了该事件,则当发行者类引发该事件时,会调用其事件处理程序方法。

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

    下面的关键字可应用于事件:
    static 即使类没有实例,调用方也能在任何时候使用该事件。 静态类和静态类成员(C# 编程指南)
    virtual 允许派生类通过使用 override 关键字来重写事件行为。 继承(C# 编程指南)
    sealed 指定对于派生类它不再属虚拟性质。
    abstract 编译器不会生成 add 和 remove 事件访问器块,因此派生类必须提供自己的实现。
    说明:
    通过使用 static 关键字,可以将事件声明为静态事件。即使类没有任何实例,调用方也能在任何时候使用静态事件。
    通过使用 virtual 关键字,可以将事件标记为虚拟事件。这样,派生类就可以通过使用 override 关键字来重写事件行为。
    重写虚事件的事件也可以为 sealed,以表示其对于派生类不再是虚事件。最后,可以将事件声明为 abstract,这意味着编译器不会生成 add 和 remove 事件访问器块。因此派生类必须提供其自己的实现。

  • 相关阅读:
    解决:Type javax.xml.bind.JAXBContext not pres
    使用RabbitMQ传输链路数据给zipkin时启动zipkin的命令
    OAuth2权限验证SQL脚本
    MD5 加密算法 All In One
    道教辟谷养生 All In One
    LattePanda 3 Delta All In One
    羊了个羊小游戏在线网页版 All In One
    How To Hack a Tech Blog Site Need Login To Copy Code All In One
    HTML5 custom input form validate All In One
    DevOps Tutorials All In One
  • 原文地址:https://www.cnblogs.com/gsk99/p/4987782.html
Copyright © 2020-2023  润新知