In C #, an event is essentially a restricted delegate. The following sample code can be used to illustrate this point:
The advantage of doing so is that you can change the response function at any time when an event occurs without modifying any code of the event class. when an event occurs, the function executed is bound at runtime.
Class Program
{
Static void main (string [] ARGs)
{
Alerteq AE = new alerteq ();
// Bind the Event Response Function
AE. Action + = new alerteq. actioneventhandler (eventhander. process );
// Event
AE. Action ("Sichuan", 6 );
AE. Action ("Sichuan", 5 );
AE. Action ("Sichuan", 3 );
}
}
// For earthquake events, action is the function of event occurrence.
Class alerteq
{
// Define the delegate
Public Delegate void actioneventhandler (Object o, earthquackargs E );
// Declare the event
Public event actioneventhandler action;
// Event occurred
Public void action (string area, int rank)
{
Earthquackargs Arg = new earthquackargs (area, rank );
Action (this, ARG );
}
}
// Capture earthquake events and handle real events
Static class eventhander
{
Public static void process (Object sender, earthquackargs message)
{
Console. writeline (sender. tostring () + "make the alert ;");
Console. writeline ("we have a" + message. Rank + "rank earthquack" + "in" + message. Area + "province! ");
}
}
// Event parameter class
Public class earthquackargs: eventargs
{
Public String area;
Public int rank;
Public earthquackargs (string area, int rank)
: Base ()
{
This. Area = area;
This. Rank = rank;
}
}