How to subscribe to other class' events in C#?

后端 未结 3 2024
旧时难觅i
旧时难觅i 2020-12-01 05:46

A simple scenario: a custom class that raises an event. I wish to consume this event inside a form and react to it.

How do I do that?

Note that the form an

相关标签:
3条回答
  • 2020-12-01 06:07

    Inside your form:

    private void SubscribeToEvent(OtherClass theInstance) => theInstance.SomeEvent += this.MyEventHandler;
    
    private void MyEventHandler(object sender, EventArgs args)
    {
        // Do something on the event
    }
    

    You just subscribe to the event on the other class the same way you would to an event in your form. The three important things to remember:

    1. You need to make sure your method (event handler) has the appropriate declaration to match up with the delegate type of the event on the other class.

    2. The event on the other class needs to be visible to you (ie: public or internal).

    3. Subscribe on a valid instance of the class, not the class itself.

    0 讨论(0)
  • 2020-12-01 06:08
    public class EventThrower
    {
        public delegate void EventHandler(object sender, EventArgs args) ;
        public event EventHandler ThrowEvent = delegate{};
    
        public void SomethingHappened() => ThrowEvent(this, new EventArgs());
    }
    
    public class EventSubscriber
    {
        private EventThrower _Thrower;
    
        public EventSubscriber()
        {
            _Thrower = new EventThrower();
            // using lambda expression..could use method like other answers on here
    
            _Thrower.ThrowEvent += (sender, args) => { DoSomething(); };
        }
    
        private void DoSomething()
        {
           // Handle event.....
        }
    }
    
    0 讨论(0)
  • 2020-12-01 06:29

    Assuming your event is handled by EventHandler, this code works:

    protected void Page_Load(object sender, EventArgs e)
    {
        var myObj = new MyClass();
        myObj.MyEvent += new EventHandler(this.HandleCustomEvent);
    }
    
    private void HandleCustomEvent(object sender, EventArgs e)
    {
        // handle the event
    }
    

    If your "custom event" requires some other signature to handle, you'll need to use that one instead.

    0 讨论(0)
提交回复
热议问题