委托实质
1.委托是方法指针;
2.委托是一个类,当对其进行实例化的时候,要将引用方法作为它的构造方法的参数。
添加event关键字保护委托:在外的赋值都会报错。
class FileUploader { public delegate void FileUploadHandler(int progress); public FileUploadHandler FileUploaded; public void Upload() { int fileProgress = 100; while (fileProgress > 0) { fileProgress--; if(FileUploaded != null) { FileUploaded(fileProgress); } } } public FileUploader() { } }
static void Main(string[] args) { FileUploader f1 = new FileUploader(); f1.FileUploaded = Progress; //f1.FileUploaded = null; f1.FileUploaded += ProgressAnother; f1.Upload(); } public static void Progress(int progress) { Console.WriteLine(progress); } public static void ProgressAnother(int progress) { Console.WriteLine(string.Format("另一个通知方法:{0}", progress)); }
标准事件模型:public delegate void EventHandler(object sender, EventArgs e)
1.委托类型的名称以EventHandler结束;
2.委托原型返回值为void;
3.委托原型具有两个参数:sender表示事件触发者,e表示事件参数;
4.事件参数的名称以EventArgs结束。
实现标准的事件模型:
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); } } } public FileUploader() { } public class FileUploadedEventArgs : EventArgs { public int FileProgress { get; set; } } }
static void Main(string[] args) { FileUploader f1 = new FileUploader(); f1.FileUploaded += Progress; //f1.FileUploaded = null; f1.FileUploaded += ProgressAnother; f1.Upload(); } public static void Progress(object sender, FileUploadedEventArgs e) { Console.WriteLine(e.FileProgress); } public static void ProgressAnother(object sender, FileUploadedEventArgs e) { Console.WriteLine(string.Format("另一个通知方法:{0}", e.FileProgress)); }
委托分为:方法委托和事件委托。
方法委托在调用的时候需要传值,且没有event修饰。
事件委托多了event修饰。使用事件应该由发布者触发而不是客户端触发。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】