From: http://jimmyloveforever.blog.163.com/blog/static/119775247200951303935836/ 1, C # The event mechanism is based on the delegate implementation, so we need to first define a delegate eventhandler:
Public Delegate void eventhandler (object from, myeventargs e) system. eventargs is the base class of the class containing event data. You can directly use the eventargs class in the code. The myeventargs class is derived from the eventargs class to implement the function of customizing event data. Here, from indicates the event object.
2. Define the event format as follows:
The delegate name of an event, such as the event textout definition:
Public event eventhandler textout;
3. Event activation is generally written as follows:
If (textout! = NULL)
Textout (this, new eventargs ());
Check whether the textout event has been subscribed. If it is not null, a user has subscribed to the event. Which of the following events is subscribed?
Testapp class, first instantiate eventsource, and then subscribe to the event:
Evsrc. textout + = new eventsource. eventhandler (catchevent );
You can also cancel the subscription:
Evsrc. textout-= new eventsource. eventhandler (catchevent );
View code
Using system; using system. collections. generic; using system. LINQ; using system. text; // define the event containing the data public class myeventargs: eventargs {private string strtext; Public myeventargs (string strtext) {This. strtext = strtext;} Public String getstrtext {get {return strtext ;}}// class eventsource {myeventargs evargs = new myeventargs ("trigger event") of the event publishing class "); // define the delegate Public Delegate void eventhandler (Object sender, myeventargs E); // define the event public event eventhandler textout; // The method for activating the event public void triggerevent () {If (textout = NULL) textout (this, evargs) ;}// class testapp of the subscribed event {public static void main () {eventsource evsrc = new eventsource (); // subscribes to the evsrc event. textout + = new eventsource. eventhandler (catchevent); // triggers the evsrc event. triggerevent (); console. writeline ("------"); // cancels the subscription event evsrc. textout-= new eventsource. eventhandler (catchevent); // triggers the evsrc event. triggerevent (); console. writeline ("------"); // The Event subscription has been canceled and testapp theapp = new testapp (); evsrc is not executed. textout + = new eventsource. eventhandler (theapp. instancecatch); evsrc. triggerevent (); console. writeline ("------");} // static method for processing events public static void catchevent (object from, myeventargs e) {console. writeline ("catchevent: {0}", E. getstrtext);} // public void instancecatch (object from, myeventargs e) {console. writeline ("instancecatch: {0}, E. getstrtext ");}}