Understanding events and event handlers in C#

后端 未结 12 1518
野性不改
野性不改 2020-11-22 04:06

I understand the purpose of events, especially within the context of creating user interfaces. I think this is the prototype for creating an event:

public vo         


        
12条回答
  •  再見小時候
    2020-11-22 04:41

    That is actually the declaration for an event handler - a method that will get called when an event is fired. To create an event, you'd write something like this:

    public class Foo
    {
        public event EventHandler MyEvent;
    }
    

    And then you can subscribe to the event like this:

    Foo foo = new Foo();
    foo.MyEvent += new EventHandler(this.OnMyEvent);
    

    With OnMyEvent() defined like this:

    private void OnMyEvent(object sender, EventArgs e)
    {
        MessageBox.Show("MyEvent fired!");
    }
    

    Whenever Foo fires off MyEvent, then your OnMyEvent handler will be called.

    You don't always have to use an instance of EventArgs as the second parameter. If you want to include additional information, you can use a class derived from EventArgs (EventArgs is the base by convention). For example, if you look at some of the events defined on Control in WinForms, or FrameworkElement in WPF, you can see examples of events that pass additional information to the event handlers.

提交回复
热议问题