采用 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. mysql localhost登录和tcp/ip登录 strace

    http://blog.itpub.net/15480802/viewspace-1755100/

  2. Activex 数字签名

    本次使用makecert的命令如下: makecert -sv online.pvk -n "CN=中国在线" -ss My -r -b 01/01/1900 -e 01/01/9 ...

  3. mmap函数使用

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

  4. Python的__getattribute__ vs __getattr__的妙用

    这里的属性即包括属性变量,也包括属性方法.即类的变量和方法. 当访问某个实例属性时, getattribute会被无条件调用,如未实现自己的getattr方法,会抛出AttributeError提示找 ...

  5. ASP.NET 5 Beta6发布了(翻译)

    感觉就好像我们刚刚发布了一个版本,现在我们又要发布一个新的版本.开发团队通过努力工作在Visual Studio2015的正式版上提交使用ASP.NET 5开发工具的上的更新以及库的更新.新的版本为b ...

  6. 文字尺寸、宽高的测量 Paint FontMetrics

    Paint.FontMetrics类简介 Google文档中的描述: ) throw new IndexOutOfBoundsException(); if (bounds == null) thro ...

  7. Node.js:Express 框架

    Express 是一个简洁而灵活的 node.js Web应用框架, 提供了一系列强大特性帮助你创建各种 Web 应用,和丰富的 HTTP 工具.使用 Express 可以快速地搭建一个完整功能的网站 ...

  8. 设置 IE 默认模式为 IE8

    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

  9. 【转】6 Reasons Why JavaScript’s Async/Await Blows Promises Away (Tutorial)

    原文:https://hackernoon.com/6-reasons-why-javascripts-async-await-blows-promises-away-tutorial-c7ec105 ...

  10. Token_使用JWT生成token

    1.token三部分 header   { "typ": "JWT", "alg": "HS256"   } paylo ...