Assume that there is a mailmanager class that is responsible for receiving emails. The mailmanager class exposes a newmail event. When a new email is received, the newmail event is triggered, cause the mail to be delivered to the mail processing object (fax and pager objects ).
Step 1: define the type to hold all the messages that need to be sent to the mail processing objects (fax and pager objects;
Class newmaileventargs: eventargs // {private string from; // Private string to; // Private string subject for the recipient; // public newmaileventargs (string from, string to, string subject) {This. from = from; this. to = to; this. subject = subject;} Public String from {get {return from ;}} public string to {get {return to ;}} Public String subject {get {return subject ;}}}
Step 2: Define the delegate type
Delegate void myeventhandler (newmaileventargs E ); // define the delegate type // the CLR event model is based on the delegate // in general, the delegate type defined here is used to set the event member and event processing method in different bind together in the class
Step 3: Define event members for the mailmanger class
Class mailmanger {public event myeventhandler newmail; // create the event member public void onnewmail (newmaileventargs e) // method to trigger the event and receive a new email {If (newmail! = NULL) {newmail (e );}}}
Step 4: Define event handling methods in the fax and pager classes
Class Fax {public void mail (newmaileventargs e) {console. writeline ("email sender:" + E. from + "recipient" + E. to + "mail title" + E. subject); console. writeline ("fax mail is being processed !!!!!!! ") ;}} Class pager {public void mail (newmaileventargs e) {console. writeline ("email sender:" + E. from + "recipient" + E. to + "mail title" + E. subject); console. writeline ("pager mail is being processed !!!!!!! ");}}
The fax and pager classes receive the same event notification information, but their processing methods can be different.
Simulate receiving an email:
Mailmanger mail = new mailmanger (); newmaileventargs E = new newmaileventargs ("me", "hello", "Hello, Hope !!! "); // Mail Information Fax = new fax (); pager = new pager (); mail. newmail + = new myeventhandler (pager. mail); // bind the event and event handling method mail. newmail + = new myeventhandler (fax. mail); mail. onnewmail (E); // call the event processing method when an email is triggered.
Preliminary event Learning