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

后端 未结 3 2115
旧时难觅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: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.....
        }
    }
    

提交回复
热议问题