c# 编码规范之事件模型规范

C#的编码规范EventHandler的原型声明:
public delegate void EventHandler(object sender,EventArgs e);

微软为事件模型设定的几个规范:
①、委托类型的名称以EventHandler结束;
②、委托原型返回值为void;
③、委托原型具有两个参数: sender表示事件触发者,e表示事件参数;
④、事件参数的名称以EventArgs结束.

    public class FileUploadedEventArgs : EventArgs {
        public int FileProgress { get; set; }
    }

    public class FileUploader {
        public event EventHandler<FileUploadedEventArgs> FileUploaded;

        public void Upload() {
            var e = new FileUploadedEventArgs() { FileProgress = 100 };
            while (e.FileProgress > 0) {
                e.FileProgress--;
                if (FileUploaded != null) FileUploaded(this, e);
            }
        }
    }

    public static void Progress(object sender,FileUploadedEventArgs e) {
        Debug.WriteLine(e.FileProgress);
    }

    public void Test() {
        var fl = new FileUploader();
        fl.FileUploaded += Progress;
        fl.Upload();
    }

摘自《编写高质量代码改善C#程序的157个建议》一书

posted @ 2021-07-05 17:08  狼王爷  阅读(65)  评论(0编辑  收藏  举报