The code below:
Step 1: Define a type to accommodate all additional information that needs to be sent to the Event Notification recipient
internal class NewMailEventArgs : EventArgs{ private readonly String m_from,m_to,m_subject; Public NewMailEventArgs(string from,string to,string subject){ m_from=from;m_to=to;m_subject=subject; } public string From{get{return m_from;}} Public string To{get{return m_to;}} Public string Subject{get{return m_subject;}} }
Note: EventArgs is only a base type that inherits other types. Many events do not have any additional information to transmit, but in our scenario, NewMailEventArgs is constructed to transmit mail information.
internal class MailManager{ public event EventHandler<NewMailEventArgs> NewMail;}
Note: NewMail is the name of this event. The event member type is EventHandler <NewMailEventArgs>. Therefore, the method prototype must take the following form:
Void MethodName (Object sender, NewMailEventArgs e );
Step 3: Define a method to notify the event registration object
Internal class MailManager {protected virtual void OnNewMail (NewMailEventArgs e) {// for thread security reasons, copy the reference of the delegate field to a temporary field EventHandler <NewMailEventArgs> temp = Interlocked. compareExchange (ref NewMail, null, null); // if (temp! = Null) temp (this, e );}}
internal class MailManager{ public void SimulateNewMail(string from,string to,string subject){ NewMailEventArgs e = new NewMailEventArgs(from,to,subject); OnNewMail(e); }}
Design the listener event type. Next we use the Fax type to use the event.
Internal sealed Class Fax {public Fax (MailManager mm) {mm. newMail + = FaxMsg;} // when a new email arrives, MailManager will call this method Private Void FaxMsg (object sender, NewMailEventArgs e) {Console. writeLine ("event triggered");} // execute this method. The Fax object will log out of its attention to the NewMail event Public Void Unregister (MailManager mm) {mm. newMail-= FaxMsg ;}}
Note: the C # compiler translates the + = Operator into the following code to add the object's attention to the event:
Mm. add_NewMail (new EventHandler <NewMailEventArgs> (this. FaxMsg ));
In this way, our example is complete. When a new mail is received, all methods of attention to mail events will be triggered, that is, the FaxMsg method in the example. The example helps you understand the event.