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

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

提交回复
热议问题