简体   繁体   中英

How to notify all subscriber classes about a raised event in one class?

I am learning how to use events around classes to notify 2 classes if an even occurs in one class. I have created the following.

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");
        }

    }

}

I want the HandleEvent method of both Class one and Two to be triggered once the button is clicked. But I am seeing event raised in Program class only. How to achieve this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM