欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

发布基于 EventHandler 模式的事件

程序员文章站 2022-05-27 23:46:25
...

一、随事件一起发送自定义数据且不使用泛型

1、如果随事件一起发送自定义数据,将自定义数据的类声明为对发布服务器和订阅者类均可见的范围。 然后添加所需成员以保留自定义事件数据。 在此示例中,将返回一个简单的字符串。

public class CustomEventArgs : EventArgs  
{  
    public CustomEventArgs(string s)  
    {  
        msg = s;  
    }  
    private string msg;  
    public string Message  
    {  
        get { return msg; }  
    }   
}

 2、声明发布类中的委托。 为以 EventHandler 结尾的委托命名。 第二个参数指定自定义 EventArgs 类型。

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

 3、定义事件,将委托声明为类型。

public event CustomEventHandler RaiseCustomEvent;

 

二、如果不随事件发送自定义数据。

如果没有任何自定义 EventArgs 类,事件类型将为非泛型 EventHandler 委托。 你无需声明该委托,因为它已在创建 C# 项目时包括的 System 命名空间中声明。 将以下代码添加到发布服务器类。

public event EventHandler RaiseCustomEvent;

 三、随事件一起发送自定义数据且使用泛型。

则无需自定义委托。 而是在发布类中,将事件类型指定为 EventHandler<CustomEventArgs>,替换尖括号中自定义类的名称。

public event EventHandler<CustomEventArgs> RaiseCustomEvent;

 

示例

下例通过使用自定义 EventArgs 类和 EventHandler<TEventArgs> 作为事件类型来演示之前的步骤。

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 += $" at {DateTime.Now}";

                // 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();

        }
    }
}

 

 

相关标签: Event delegate