Follow these steps to customize events:
1. Define Delegation
2. Define the event publisher class
Declare events
Define event parameter classes
Define the on method of the event (directly execute the event)
Define the method for triggering an event (including the trigger condition. Call the on method when the condition is met)
3. Define the event subscriber class (there can be multiple subscriber classes)
Define event processingProgramMethod
4. register an event
Instantiate publisher and subscriber
Bind an instantiated delegate with the event handler method as the parameter on the publisher event to complete event registration.
5. Use Events
Execute the method to trigger the event in the publisher.
The specific example is as follows: **************************************** **************************************** ***********
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Namespace delegate_event
{
// Define the event publisher class
Public class publisher
{
Private int count;
Public string name = "publisher ";
// Define the delegate
Public Delegate void numberchangedeventhandler (Object sender, someeventargs E );
Public event numberchangedeventhandler numberchanged; // declare an event
// defines the someeventargs class and transmits the information that the subscriber is interested in. This is a class in the class
public class someeventargs: eventargs
{< br> Public readonly int count;
Public someeventargs (INT count)
{< br> This. count = count;
}< BR >}
// define the onxxx method of the call event for other trigger methods
protected virtual void onnumberchanged (someeventargs e)
{< br> If (numberchanged! = NULL)
{// trigger event
numberchanged (this, e);
}< BR >}
// method for defining the trigger event
Public void dosomething ()
{< br> for (INT I = 0; I <15; I ++)
{< br> count ++;
If (count> = 10) // trigger condition
{< br> someeventargs E = new someeventargs (count);
onnumberchanged (E); // call method, to raise the event
}< BR >}
// define event subscriber
public class subscriber
{< br> // event handler
Public void onnumberchanged (Object sender, publisher. someeventargs e) // pay attention to the methods with the same name as the method in the publisher. They have different parameters and do not work.
{< br> publisher = (publisher) sender;
console. writeline ("subscriber Notified: {0}, Count = {1}", publisher. name, E. count);
}< BR >}
class Program
{< br> static void main (string [] ARGs)
{< br> publisher pub = new publisher ();
subscriber sub = new subscriber ();
pub. numberchanged + = new publisher. numberchangedeventhandler (sub. onnumberchanged);
pub. dosomething (); // events should be triggered using dosomething ()
console. readkey ();
}< BR >}