zoukankan      html  css  js  c++  java
  • C# 事件

    1.一般事件:

           发布者(类FaBuZhe)中定义事件: 

            1). 声明委托类型: public delegate void CustomEventHandler(object sender, EventArgs e);
            2). 创建CustomEventHandler的实例(CustomEvent事件):public event CustomEventHandler CustomEvent;

          

            3).订阅者(类DingYueZhe):持有发布者的对象并用其注册事件

                        FaBuZher faBuzhe = new FaBuZhe();
                        faBuZhe.CustomEvent += new FaBuZhe.CustomEventHandler(DoOnCustomEvent);

            
            4). 发布者触发事件:

                       faBuZhe.CustomEvent(this, eventArgs); //拓展:线程安全如何处理,参看《CLR via C# 第三版》

            5).订阅者被通知后,决定干点事:

            void DoOnCustomEvent(object sender, EventArgs e)

            {

                  ..... ;//do something here

            }

    2.泛型事件:

           发布者(类FaBuZhe)中定义事件: 

            1). 声明委托类型的对象: public delegate void CustomEventHandler(object sender, EventArgs e);
            2). 创建泛型事件的实例CustomEvent:public event EventHandler<EventArgsCustomEvent = delegate { };

            3).订阅者(类DingYueZhe):持有发布者的对象并用其注册事件

                        FaBuZher faBuzhe = new FaBuZhe();
                        faBuZhe.CustomEvent += new EventHandler<EventArgs>(DoOnCustomEvent);

            
            4). 发布者触发事件:

                   //使用foreah循环调用GetInvocationList是为了处理来自订阅者的异常

                    foreach (EventHandler<EventArgs> hanlder in CustomEvent.GetInvocationList())
                    {
                        //  faBuZhe.CustomEvent(this, eventArgs);//拓展:线程安全如何处理,参看《CLR via C# 第三版》
                        hanlder(this, eventArgs);
                    }

            5).订阅者被通知后,决定干点事:

            void DoOnCustomEvent(object sender, EventArgs e)

            {

                  ..... ;//do something here

            }

  • 相关阅读:
    用django搭建自己的博客
    python模块调用
    python常用函数
    ubuntu不能访问windows中的文件
    更改ubuntu下mysql的密码
    重拾代码,加油
    java 接收 char字符型
    Git基础
    flask中'bool' object has no attribute '__call__'问题
    基于python的flask的应用实例注意事项
  • 原文地址:https://www.cnblogs.com/easy5weikai/p/3670457.html
Copyright © 2011-2022 走看看