Generally, C # custom events take the following steps:
1. Declare a delegate: (defines the event type)
For example:
- Public Delegate void event name eventhandler (Object serder, eventargs E );
// The event name should be replaced by your own name, and the subsequent eventhandler is the recommended naming convention for C #. Of course, if you do not want to comply with it, you can use any character or even do not want.
If you want to customize the event parameter eventargs, You can derive your own event parameter class from this class, and then replace eventargs with your parameter class in the delegate declaration.
Note: To fully understand the principles of custom events, you need to learn about delegate.
2. Declare an event in your class and use the delegate in step 1 as the event type:
- Public event name eventhandler event name;
3. Add the event trigger method in your class.Code:
- Event name (this, new eventargs ());
Or:
- If (event name! = NULL)
- Event name (this, new eventargs ());
// If you use your own event parameter class, you can replace new eventargs () with your parameter class instance, and save the data you need to pass in your parameter class.
4. C # custom event registration:
Event registration is no different from normal event registration, that is, if an external object needs to respond when your event is triggered, then you can register the event in an external Constructor (or an appropriate location ).
- Class instance with event. event name + = new event name eventhandler (event processing method name );
5. Compile the event handling method:
- Public void event processing method name (Object sender, eventargs E)
- {
- // Add your code
- }
Note: If you handle your own trigger events in the class, you can select C # Custom Event step 4 and step 5, that is, register yourself, you can also directly call the event processing method in the trigger event code.