First, let's take a look at several classes and attributes related to events and delegation:
Delegate, multicastdelegate, eventhandler, eventhandlerlist, eventhandlerlist. listentry, control, component
The events attribute of control is inherited by system. componentmodel. component, which is an instance of eventhandlerlist.
The eventhandlerlist class has three important methods:
Public Void Addhandler ( Object Key, delegate value );
Public Void Removehandler ( Object Key, delegate value );
Private Listentry find ( Object Key );
Example: we want to add a click event for the current control ).
Step 1: Create a static read-only attribute
Public static readonly object clickevent = new object (); // It is the key (key) for future event search delegation ),
Step 2: register an event
Public event eventhandler click
{
Add
{
Base. Events. addhandler (clickevent, value );
}
Remove
{
Base. Events. removehandler (clickevent, value );
}
}
----
The following is the definition of events: Private Eventhandlerlist events;
Protected Eventhandlerlist events
{
Get
{
If ( This . Events = Null )
{
This. Events= NewEventhandlerlist ();
}
Return This . Events;
}
}