C # Delegate delegate example event-driven
Using system; Using system. Collections. Generic; Using system. text; Using system. Threading; Using system. runtime. remoting. messaging; Using system. IO; Using system. net; Namespace consoleapplication2 { /// <Summary> ///************************************* ************************************ /// Program Author: Li weitao /// QQ: 12666954 /// Send messages and drive events ///************************************* ************************************ /// </Summary>
Public struct quitperson // defines the information of the class member { Public string name; Public string class; } Class Client { Public class cquithireeventargs: eventargs { Public readonly quitperson; Public cquithireeventargs (quitperson) // encapsulate event information { This. quitperson = quitperson; } } Public Delegate void quithireeventhandler (Object sender, cquithireeventargs E); // defines the delegate Public event quithireeventhandler onquithire; // event Protected virtual void quithire (cquithireeventargs e) // event notifier { If (onquithire! = NULL) Onquithire (this, e ); } Public void setquitperson (quitperson) { Cquithireeventargs E = new cquithireeventargs (quitperson ); Quithire (E); // call the notifier to notify the subscribe of all registration events } } Class teacher { Public void report (Object sender, client. cquithireeventargs E) { Console. writeline ("{0}'s {1} class skipped! ", E. quitperson. Class, E. quitperson. Name ); } Public Teacher (client CLT) { CLT. onquithire + = new client. quithireeventhandler (report ); } } Class schoolposident { Public void sreport (Object sender, client. cquithireeventargs E) { Console. writeline ("{0 }:{ 1} class {2} skipped! ", Datetime. Now. tow.datestring (), E. quitperson. Class, E. quitperson. Name ); } Public schoolposident (client CLT) { CLT. onquithire + = new client. quithireeventhandler (sreport ); } } Class Program { Static void main (string [] ARGs) { Quitperson q = new quitperson (); // initialize the information of the class member. Q. Class = "software 051 "; Q. Name = "Li weitao "; Client CLT = new client (); // Subscribe to events Teacher T = new teacher (CLT ); Schoolposident sp = new schoolposident (CLT ); CLT. setquitperson (Q ); Console. Readline (); } }
} |