采用 EventHandler 模式发布事件

(如果不需要与事件一起发送自定义数据,请跳过此步骤,进入步骤 3a。)在发行者类和订阅方类均可看见的范围中声明自定义数据的类。 然后添加保留您的自定义事件数据所需的成员。 在此示例中,会返回一个简单字符串。

public class CustomEventArgs : EventArgs
    {
        public CustomEventArgs(string s)
        {      
            msg = s;     
         }

private string msg;

public string Message
        {
          get { return msg; }
        }
    }

(如果您使用的是 EventHandler<TEventArgs> 的泛型版本,请跳过此步骤。)在发布类中声明一个委托。 第二个参数指定自定义 EventArgs 类型。

public delegate void CustomEventHandler(object sender, CustomEventArgs a);

使用以下任一步骤,在发布类中声明事件。

如果没有自定义 EventArgs 类,事件类型就是非泛型 EventHandler 委托。 无需声明委托,因为它已在创建 C# 项目时包含的 System 命名空间中进行了声明。 将以下代码添加到发行者类中。

public event EventHandler RaiseCustomEvent;

如果使用的是 EventHandler 的非泛型版本,并且您有一个由 EventArgs 派生的自定义类,请在发布类中声明您的事件,并且将来自步骤 2 的委托用作类型。

public event CustomEventHandler RaiseCustomEvent;

如果使用的是泛型版本,则不需要自定义委托。 相反,在发行者类中,您应将事件类型指定为 EventHandler<CustomEventArgs>,将尖括号中的内容替换为自己的类的名称。

public event EventHandler<CustomEventArgs> RaiseCustomEvent;

采用 EventHandler 模式发布事件

下面的示例通过将自定义 EventArgs 类和 EventHandler<TEventArgs> 用作事件类型来演示上述步骤。
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotNetEvents
{
    using System;
    using System.Collections.Generic;

// Define a class to hold custom event info
    //自定义事件传统的数据类
    public class CustomEventArgs : EventArgs
    {
        public CustomEventArgs(string s)
        {
            message = s;
        }
        private string message;

public string Message
        {
            get { return message; }
            set { message = value; }
        }
    }

// Class that publishes an event
    //事件发布类
    class Publisher
    {

// Declare the event using EventHandler<T>
        //声明事件委托
        public event EventHandler<CustomEventArgs> RaiseCustomEvent;

public void DoSomething()
        {
            // Write some code that does something useful here
            // then raise the event. You can also raise an event
            // before you execute a block of code.
            OnRaiseCustomEvent(new CustomEventArgs("Did something"));

}

// Wrap event invocations inside a protected virtual method
        // to allow derived classes to override the event invocation behavior
        protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
        {
            // Make a temporary copy of the event to avoid possibility of
            // a race condition if the last subscriber unsubscribes
            // immediately after the null check and before the event is raised.
            EventHandler<CustomEventArgs> handler = RaiseCustomEvent;

// Event will be null if there are no subscribers
            //如果委托事件不为空时就引发事件
            if (handler != null)
            {
                // Format the string to send inside the CustomEventArgs parameter
                e.Message += String.Format(" at {0}", DateTime.Now.ToString());

// Use the () operator to raise the event.
                //引发事件
                handler(this, e);
            }
        }
    }

//Class that subscribes to an event
    //接收事件类
    class Subscriber
    {
        private string id;
        public Subscriber(string ID, Publisher pub)
        {
            id = ID;
            // Subscribe to the event using C# 2.0 syntax
            //增加事件委托中的事件
            pub.RaiseCustomEvent += HandleCustomEvent;
        }

// Define what actions to take when the event is raised.
        void HandleCustomEvent(object sender, CustomEventArgs e)
        {
            Console.WriteLine(id + " received this message: {0}", e.Message);
        }
    }

class Program
    {
        static void Main(string[] args)
        {
            Publisher pub = new Publisher();
            Subscriber sub1 = new Subscriber("sub1", pub);
            Subscriber sub2 = new Subscriber("sub2", pub);

// Call the method that raises the event.
            pub.DoSomething();

// Keep the console window open
            Console.WriteLine("Press Enter to close this window.");
            Console.ReadLine();

}
    }
}

采用 EventHandler 模式发布事件(转载)的更多相关文章

  1. Dapr实现.Net Grpc服务之间的发布和订阅,并采用WebApi类似的事件订阅方式

    大家好,我是失业在家,正在找工作的博主Jerry,找工作之余,总结和整理以前的项目经验,动手写了个洋葱架构(整洁架构)示例解决方案 OnionArch.其目的是为了更好的实现基于DDD(领域驱动分析) ...

  2. ANDROID 中设计模式的采用--行为模式

     1 职责链模式 职责链模式的意图为:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系.将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止.使多个对象都有 ...

  3. 004-spring-data-elasticsearch 3.0.0.0使用【二】-spring-data之定义方法、创建repository实例、从聚合根发布事件

    续上文 1.4.定义方法 存储库代理有两种方法可以从方法名称派生特定于存储的查询.它可以直接从方法名称派生查询,或者使用手动定义的查询.可用选项取决于实际store.但是,必须有一个策略来决定创建什么 ...

  4. Delegate,Action,Func,匿名方法,匿名委托,事件 (转载)

    Delegate,Action,Func,匿名方法,匿名委托,事件 (转载) 一.委托Delegate 一般的方法(Method)中,我们的参数总是string,int,DateTime...这些基本 ...

  5. NServiceBus入门:发布事件(Introduction to NServiceBus: Publishing events)

    原文地址:https://docs.particular.net/tutorials/intro-to-nservicebus/4-publishing-events/ 侵删. 这个教程到目前为止,我 ...

  6. Java设计模式补充:回调模式、事件监听器模式、观察者模式(转)

    一.回调函数 为什么首先会讲回调函数呢?因为这个是理解监听器.观察者模式的关键. 什么是回调函数 所谓的回调,用于回调的函数. 回调函数只是一个功能片段,由用户按照回调函数调用约定来实现的一个函数. ...

  7. STM32学习笔记(九) 外部中断,待机模式和事件唤醒

    学会知识只需要不段的积累和提高,但是如何将知识系统的讲解出来就需要深入的认知和系统的了解.外部中断和事件学习难度并不高,不过涉及到STM32的电源控制部分,还是值得认真了解的,在本文中我将以实际代码为 ...

  8. 最近开始研究PMD(一款采用BSD协议发布的Java程序代码检查工具)

    PMD是一款采用BSD协议发布的Java程序代码检查工具.该工具可以做到检查Java代码中是否含有未使用的变量.是否含有空的抓取块.是否含有不必要的对象等.该软件功能强大,扫描效率高,是Java程序员 ...

  9. 如何设置Win7系统中的上帝模式GodMode(转载)

    如何设置Win7系统中的上帝模式GodMode(转载) NT6系统中隐藏了一个秘密的“GodMode”,字面上译为“上帝模式”.God Mode其实就是一个简单的文件夹窗口,但包含了几乎所有系统的设置 ...

随机推荐

  1. mmap函数使用

    UNIX网络编程第二卷进程间通信对mmap函数进行了说明.该函数主要用途有三个:1.将一个普通文件映射到内存中,通常在需要对文件进行频繁读写时使用,这样用内存读写取代I/O读写,以获得较高的性能:2. ...

  2. C++入门级 一

    如果您想学习电脑编程,却又不知从何入手,那么您不妨看看下面的几种学习方案,可能会给您一些启示吧! 方案一 Basic语言 & Visual Basic 优点 (1)Basic 简单易学,很容易 ...

  3. java_Collection_详细介绍

    转自:http://blog.sina.com.cn/s/blog_3fb3625f0101aref.html 1.类集框架 java.util 包中包含了一些在 Java 2 中新增加的最令人兴奋的 ...

  4. getaddrinfo详解

    #include <sys/socket.h> #include <netdb.h> int getaddrinfo(const char *restrict nodename ...

  5. 如何通过.reg文件来修改注册表键和子键以及键值

    无废话, 直接上例子, 自己运行一下便知. 然后根据自己需要改改就可以随便用了.   添加key, subkey, 和设置键值的例子. ==================== Windows Reg ...

  6. Windows MongoDB安装配置

    1.下载 官网:http://www.runoob.com/mongodb/mongodb-window-install.html 由于是在window下,所以我下载的是mongodb-win32-x ...

  7. C# 网络斗地主源码开源

    C# 网络斗地主源码开源多线程 讨论交流及  下载地址 可以发送聊天消息

  8. 关于使用jquery时,ie8下提示对象不支持的属性或方法的解决办法

    转自:http://wapapp.baidu.com/auoong/item/538790fcbe87c834d7ff8cde 首先这个问题的前提是已经排除了常见的这个问题.下面说一种今天我碰到的一种 ...

  9. 10分钟,利用canvas画一个小的loading界面

    首先利用定义下canvas得样式 <canvas width="1024" height="720" id="canvas" styl ...

  10. 数组根据index拆分和查询下标

    private class ArrayTool<T> { /// <summary>查询值在数组中的下标</summary> /// <param name= ...