标签:委托 this load 进度 color delegate line span public
建议41:实现标准的事件模型
上一建议中,我们实现了一个带事件通知的文件传输类FileUploader。虽然已经满足需求,但却不符合C#的编码规范,查看EventHandler的原型声明:
public delegate void EventHandler(object sender, EventArgs e);
我们应该知道微软为事件模型定义的几个规范:
为了将FileUploader修改为符合C#的编程规范,首先需要提供一个FileUploadedEventArgs类来保存进度信息:
class FileUploadedEventArgs : EventArgs { public int FileProgress { get; set; } } class FileUploader { public event EventHandler<FileUploadedEventArgs> FileUploaded; public void Upload() { FileUploadedEventArgs e = new FileUploadedEventArgs() { FileProgress = 100 }; while (e.FileProgress > 0) {
//传输代码,省略 e.FileProgress--; if (FileUploaded != null) { FileUploaded(this, e); } } } }
调用代码:
static void Main(string[] args) { FileUploader f1=new FileUploader(); f1.FileUploaded += f1_FileUploaded;
f1.Upload(); } static void f1_FileUploaded(object sender, FileUploadedEventArgs e) { Console.WriteLine(e.FileProgress); }
转自:《编写高质量代码改善C#程序的157个建议》陆敏技
【转】编写高质量代码改善C#程序的157个建议——建议41:实现标准的事件模型
标签:委托 this load 进度 color delegate line span public
原文地址:http://www.cnblogs.com/farmer-y/p/7943799.html