首页 > 解决方案 > 如何通知所有订阅者类关于一个类中引发的事件?

问题描述

我正在学习如何使用类周围的事件来通知 2 个类,如果一个类中发生偶数。我创建了以下内容。

namespace TestConsole
{
    class Program : Form
    {
        public event EventHandler Something;
        public Program()
        {
            Button btn = new Button();
            btn.Parent = this;
            btn.Text = "Click Me.!";
            btn.Location = new Point(100, 100);
            btn.Click += Btn_Click;
            Something += HandleThis;
        }

        private void Btn_Click(object sender, EventArgs e)
        {
            
            Something(this,null);
        }
        private void HandleThis(object sender, EventArgs e)
        {
            Console.WriteLine("From Main: Something typed");
        }
        static void Main(string[] args)
        {
            Application.Run(new Program());
            Console.ReadLine();
        }
    }
    class One
    {
        One()
        {
            Program SubscriberObj = new Program();
            SubscriberObj.Something += HandleEvent;
        }

        private void HandleEvent(object sender, EventArgs e)
        {
            Console.WriteLine("From One: Something typed");
        }
    }

    class Two
    {
        Two()
        {
            Program SubscriberObj = new Program();
            SubscriberObj.Something += HandleEvent;
        }

        private void HandleEvent(object sender, EventArgs e)
        {
            Console.WriteLine("From Two: Something typed");
        }

    }

}

我希望在单击按钮后触发第一类和第二类的 HandleEvent 方法。但我只看到在 Program 课程中引发的事件。如何做到这一点?

标签: c#.neteventsdelegatesnotify

解决方案


You do not create an instance of One and Two. Therefore, no class will register for this event. Also, you create new instances of program in One and Two. But you need the same instance in which the event is fired. You must pass the instance of program in the constructor. You should also always check if the handler is null when the event gets fired.

    EventHandler handler = Something;
    handler?.Invoke(this, new EventArgs());

This code is equivalent to:

    EventHandler handler = Something;
    if (handler != null)
    {
        handler.Invoke(this, new EventArgs());
    }

推荐阅读