Recent reading on the content of the event, before writing WinForm, events are directly used, the internal wording is not understood.
This will customize an event.
First, write a class.
Public classNewmaileventargs:eventargs//This class is later a parameter of the event that is used to pass some additional information about the event. But must inherit EventArgs { Private ReadOnly stringM_from, m_to, M_subject; PublicNewmaileventargs (string from,stringTo,stringsubject) {M_from= from; M_to=to ; M_subject=subject; } Public stringfrom {Get{returnM_from;} } Public stringto {Get{returnm_to;} } Public stringSubject {Get{returnM_subject;} } }
Write another class, which is something about the event.
Public classMailmanager { Public EventEventhandler<newmaileventargs> NewMail;//Define an event, in fact it is a paradigm delegate. This delegate requires two parameters. You can press F12 to follow the definition of this delegate
// Define an Event trigger method, here for type safety, claim protect protected Virtual voidOnnewmail (Newmaileventargs e)//The class defined above, used here as a parameter, to pass information{//because time can be called in many places, for type safety, here is not the direct manipulation of the NewMail eventeventhandler<newmaileventargs> temp = Volatile.read (refNewMail); if(Temp! =NULL) Temp ( This, E); } //exposes a method for converting input into an expected event, triggering an event Onnewmail Public voidSimulatenewmail (string from,stringTo,stringsubject) {Newmaileventargs e=NewNewmaileventargs ( from, To,subject); Onnewmail (e); } }
Here's the definition and triggering event.
classProgram {Static voidMain (string[] args) {Mailmanager Mail=NewMailmanager (); Mail. NewMail+ = Mail_newmail;//Create EventMail. Simulatenewmail ("Hahah","HSHSHS","Ksksksk");//Trigger This eventMail. NewMail-= Mail_newmail;//Destroying Events } Static voidMail_newmail (Objectsender, Newmaileventargs e) {Console.WriteLine ("faxing mail message:"); Console.WriteLine ("from={0},to={1},subject={2}", E.from, e.to, E.subject); Console.readkey (); } }
Write an event (not just add an event to the control)------------C #