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

坚强是说给别人听的谎言 提交于 2019-11-27 07:28:06
        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.....
            }
        }

Inside your form:

void SubscribeToEvent(OtherClass theInstance)
{
    theInstance.SomeEvent += this.MyEventHandler;
}

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.

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

protected void Page_Load(object sender, EventArgs e)
{
    MyClass 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!