Recommendation 41: Implementing a standard event model
In the previous recommendation, we implemented a file transfer class Fileuploader with event notification. Although the requirements have been met, but do not conform to C # coding specifications, view EventHandler's prototype declaration:
Public Delegate void EventHandler (object sender, EventArgs e);
We should know a few of the specifications Microsoft defines for the event model:
- The name of the delegate type has EventHandler ended;
- The return value of the delegate prototype is void;
- The delegate prototype has two parameters: Sender represents the event trigger, and E represents the event argument;
- The name of the event argument ends with EventArgs.
To modify Fileuploader to conform to the C # Programming specification, you first need to provide a Fileuploadedeventargs class to hold the progress information:
classFileuploadedeventargs:eventargs { Public intfileprogress {Get;Set; } } classFileuploader { Public EventEventhandler<fileuploadedeventargs>fileuploaded; Public voidUpload () {Fileuploadedeventargs e=NewFileuploadedeventargs () {fileprogress = - }; while(E.fileprogress >0) {
//Transfer code, omit e.fileprogress--; if(fileuploaded! =NULL) {fileuploaded ( This, E); } } } }
Calling code:
Static void Main (string[] args) { Fileuploader f1=new fileuploader (); + = f1_fileuploaded;
F1. Upload (); } Static void f1_fileuploaded (object sender, Fileuploadedeventargs e) { Console.WriteLine (e.fileprogress); }
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 41: Implementing a standard event model