The component class supports the event chain by default. By operating its events attribute, You can greatly simplify the logic for adding and removing events.
Events is a set of key-eventhandler, but it is not implemented by hash table. The specific implementation method is not described here.
Any subclass inherited from component can benefit from this benefit. If you need to add events, you can handle them as follows:
Let me explain the details first:
If we want to add an eventhandler-form delegate as the event type: Return void, the parameter list is (object, eventargs ),
We recommend that you add a subclass of eventargs and use the generic eventhandler <t> as the event type. This reduces the number of delegate type declarations.
From another perspective, any custom event can be in this form. The only difference is that the subclass of eventargs needs to be implemented as needed.
Example
// Define an event parameter subclass inherited from eventargs
Public class takscompletedeventargs: eventargs {}
// The general practice is to define an event variable and then perform the Add/Remove operation of eventhandler.
Public class eventsamplenormal
{
// Define the event member variable
Private event eventhandler taskcompleted;
Public event eventhandler taskcompleted
{
Add {taskcompleted + = value ;}
Remove {taskcompleted-= value ;}
}
// Define the trigger function
Protected virtual void ontaskcompleted (takscompletedeventargs E)
{
If (taskcompleted! = NULL)
{
Taskcompleted (this, e );
}
}
}
// Inherit component to add events
Public class eventsamplecomponent: Component
{
// Define an event key
Private Static readonly object eventtaskcompleted;
// Initialize eventkey in the static Constructor
Static eventsamplecomponent ()
{
Eventtaskcompleted = new object ();
}
// Define the event
Public event eventhandler taskcompleted
{
Add {events. addhandler (eventtaskcompleted, value );}
Remove {events. removehandler (eventtaskcompleted, value );}
}
// Define the trigger function
Protected virtual void ontaskcompleted (takscompletedeventargs E)
{
VaR handler = This. events [eventtaskcompleted] As eventhandler;
If (handler! = NULL)
{
Handler (this, e );
}
}
}
BTW: If you use reflector and other decompilation tools to view the Framework Code, you will find that all the general control events are implemented in the second way.