采用 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. java反射机制简单介绍

    1.字节码.所谓的字节码就是当java虚拟机载入某个类的对象时,首先须要将硬盘中该类的源码编译成class文件的二进制代码(字节码),然后将class文件的字节码载入到内存中,之后再创建该类的对象 2 ...

  2. Linux系统中/dev/mtd与/dev/mtdblock的区别,即MTD字符设备和块设备的区别

    转:http://www.crifan.com/linux_system_in__dev__mtd_and__dev__mtdblock_distinction_character_devices_a ...

  3. Springboot集成Jedis + Redisson(已自测)

    原文:https://blog.csdn.net/c_zyer/article/details/79415728 本文主要跟大家分享在Springboot中集成Jedis和Redisson的方法.为什 ...

  4. sql 循环插入某一条数据

    declare @i int set @i=1 while @i<(10000)begin INSERT INTO [Table]( [IDi] ,[IDo] ,[Synci] ) ( SELE ...

  5. 机器学习: 神经网络中的Error函数

    利用神经网络做分类的时候,可以将神经网络看成一个mapping function,从输入到输出经过复杂的非线性变换.而输出的预测值与实际的目标值总是存在一定偏差的,一般利用这种偏差建立error 函数 ...

  6. Latex作者单位的写法—AND 首页脚注

    IEEE会议的模板 以四个作者为例 正常: 作者单位如果名字较短,可以直接写在作者对应的下面,邮箱可以对应写在再接下来的下面. 一 如果邮箱较长,可以用\thanks{ }命令将其变为脚注.例如: ~ ...

  7. Ajax技术——与服务器通信

    1. 发送请求 Ajax可以通过XMLHttpRequest对象实现采用异步方式在后台发送请求.通常情况下,Ajax发送请求有两种,一种是发送GET请求,另一种是发送POST请求.但是无论发送哪种请求 ...

  8. 如何获取Android唯一标识(唯一序列号)

    有很多场景和需求你需要用到手机设备的唯一标识符. 在Android中,有以下几种方法获取这样的ID. 1. The IMEI: 仅仅只对Android手机有效: 1 2 TelephonyManage ...

  9. GPGPU OpenCL使用结构体数据

    OpenCL编程中可以使用结构体,只需要在核函数kernel中提供同样的结构体申明就可以啦. 如果在主函数中定义了结构体: typedef struct studentNode{ int age; f ...

  10. 9个实用的Javascript代码高亮脚本

    代码高亮很有用,特别是在需要在网站或者blog中显示自己编写的代码的时候,或者给其他人查看或调试语法错误的时候.我们可以将代码高亮,以便阅读者可以十分方便的读取代码块,增加用户阅读代码的良好体验. 目 ...