Recommendation 40: Use the event keyword to apply protection to delegates
In the proposal we implemented a file transfer class with the notification function, as follows:
classFileuploader { Public Delegate voidFileuploadedhandler (intprogress); PublicFileuploadedhandler fileuploaded; Public voidUpload () {intFileprogress = -; while(Fileprogress >0) { //transfer code, omitfileprogress--; if(fileuploaded! =NULL) {fileuploaded (fileprogress); } } } }
Call like this:
Static voidMain (string[] args) {Fileuploader F1=NewFileuploader (); F1. fileuploaded=Progress; F1. fileuploaded=Progressanother; F1. Upload (); Console.read (); } Static voidProgress (intprogress) {Console.WriteLine (progress); } Static voidProgressanother (intprogress) {Console.WriteLine ("Another method: {0}", progress); }
The above caller code itself is in conjunction with the Fileuploader class, which has at least two questions:
1) If another thread is in main, the worker thread can set the fileprogress delegate chain to null:
null;
2) fileuploaded can be called externally, such as:
F1. Fileuploaded (ten);
This should not be allowed, because when the caller is notified, it should be the Fileuploader class's own responsibility, rather than the caller itself to decide. The event keyword is raised in this case, and it is protected by the delegate.
Will
Public Fileuploadedhandler fileuploaded;
Switch
Public Event Fileuploadedhandler fileuploaded;
In this way, several of the above mentioned situations are blocked:
Null== progressanother;
The above code will compile without passing:
Event "MyTest.FileUploader.FileUploaded" can only appear to the left of + = or-= (except when used from type "Mytest.fileuploader")
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 40: Use the event keyword to enforce protection for delegates