Raise an event of a class from a different class in C#

后端 未结 12 892
庸人自扰
庸人自扰 2020-11-28 07:44

I have a class, EventContainer.cs, which contains an event, say:

public event EventHandler AfterSearch;

I have another class, EventRaiser.c

12条回答
  •  [愿得一人]
    2020-11-28 08:10

    The raising class has to get a fresh copy of the EventHandler. One possible solution below.

    using System;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            class HasEvent
            {
                public event EventHandler OnEnvent;
                EventInvoker myInvoker;
    
                public HasEvent()
                {
                    myInvoker = new EventInvoker(this, () => OnEnvent);
                }
    
                public void MyInvokerRaising() {
                    myInvoker.Raise();
                }
    
            }
    
            class EventInvoker
            {
                private Func GetEventHandler;
                private object sender;
    
                public EventInvoker(object sender, Func GetEventHandler)
                {
                    this.sender = sender;
                    this.GetEventHandler = GetEventHandler;
                }
    
                public void Raise()
                {
                    if(null != GetEventHandler())
                    {
                        GetEventHandler()(sender, new EventArgs());
                    }
                }
            }
    
            static void Main(string[] args)
            {
                HasEvent h = new HasEvent();
                h.OnEnvent += H_OnEnvent;
                h.MyInvokerRaising();
            }
    
            private static void H_OnEnvent(object sender, EventArgs e)
            {
                Console.WriteLine("FIRED");
            }
        }
    }
    

提交回复
热议问题