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

            }

  • 相关阅读:
    jsp实现登陆功能小实验
    netty
    shiro
    mybatis
    spring MVC
    spring
    集合框架面试题
    Redis面试题
    Dubbo面试题汇总
    阿里面试题
  • 原文地址:https://www.cnblogs.com/easy5weikai/p/3670457.html
Copyright © 2011-2022 走看看