/// <summary> ///event Data/// </summary> Internal Sealed classNewmaileventargs:eventargs {Private ReadOnlyString M_from, m_to, M_subject; PublicNewmaileventargs (String from, string to, string subject) {M_from= from; M_to = to; M_subject =subject; } /// <summary> ///Sender/// </summary> PublicString from {Get{returnM_from;} } /// <summary> ///Recipient/// </summary> PublicString to {Get{returnm_to;} } /// <summary> ///title/// </summary> PublicString Subject {Get{returnM_subject;} } } Internal classMailmanager {PrivateEventhandler<newmaileventargs>M_newmail; //Event Properties Public EventEventhandler<newmaileventargs>NewMail {add {m_newmail+=value; } Remove {M_newmail-=value; } } protected Virtual voidOnnewmail (Newmaileventargs e) {//eventhandler<newmaileventargs> temp =//Interlocked.compareexchange (ref m_newmail, NULL, NULL); //if (temp! = null) Temp (this, e); if(M_newmail! =NULL) {M_newmail.invoke ( This, E); } } /// <summary> ///simulate new messages/// </summary> /// <param name= "from" ></param> /// <param name= "to" ></param> /// <param name= "Subject" ></param> Public voidSimulatenewmail (String from, string to, string subject) {Newmaileventargs e=NewNewmaileventargs ( from, to, subject); Onnewmail (e); } } /// <summary> ///Fax/// </summary> Internal Sealed classFax { PublicFax (mailmanager mm) {mm. NewMail+=faxmsg; } Private voidfaxmsg (Object sender, Newmaileventargs e) {Console.WriteLine ("Fax e-mail information:"); Console.WriteLine ("from={0}, To={1}, subject={2}", E.from, e.to, E.subject); } Public voidUnregister (mailmanager mm) {mm. NewMail-=faxmsg; } } Internal Sealed classPager { PublicPager (mailmanager mm) {mm. NewMail+=Sendmsgtopager; } Private voidSendmsgtopager (Object sender, Newmaileventargs e) {Console.WriteLine ("Send mail to pager:"); Console.WriteLine ("from={0}, To={1}, subject={2}", E.from, e.to, E.subject); } Public voidUnregister (mailmanager mm) {mm. NewMail-=Sendmsgtopager; } }
Client:
Static voidMain (string[] args) { //Construct a Mailmanager objectMailmanager mm =NewMailmanager (); //Construct a Fax object passing it the Mailmanager objectFax Fax =NewFax (mm); //Construct a Pager object passing it the Mailmanager objectPager Pager =NewPager (mm); //simulate an incoming mail messageMm. Simulatenewmail ("Jeffrey","Kristin","I Love you!"); //Force the Fax object to unregister itself with the MailmanagerFax. Unregister (mm); //simulate an incoming mail messageMm. Simulatenewmail ("Jeffrey","Mom & Dad","Happy Birthday."); }
C # Events