C#_事件
2024-10-15 13:05:08
C#_事件
概述
今天用来演示事件的例子是模拟实现一个文件下载类,在这个类中我将定义一个DownLoad事件,这个事件用来在文件下载的过程中,向订阅这个事件的用户发出消息,而这个消息将用DownLoadEventArgs类来封装,这个消息类中定义一个percent字段,用来保存当前已下载文件的百分比,下面请看官欣赏过程:
一、定义要发送给用户(订阅事件者)的消息类
1 internal class DownLoadEventArgs: EventArgs
2 {
3 private readonly Int32 _percent; //文件下载百分比
4 public DownLoadEventArgs(Int32 percent)
5 {
6 _percent = percent;
7 }
8
9 public Int32 Percent
10 {
11 get
12 {
13 return _percent;
14 }
15 }
16 }
二、定义文件下载类
这个类中定义一个DownLoad事件,一个当事件发生时通知用户(事件订阅者)的方法OnFileDownloaded,一个文件下载方法FileDownload,如下:
1 internal class FileManager
2 {
3 public event EventHandler<DownLoadEventArgs> DownLoad; //定义事件
4
5
6 protected virtual void OnFileDownloaded(DownLoadEventArgs e)
7 {
8 EventHandler<DownLoadEventArgs> temp = DownLoad;
9 if(temp != null)
10 {
11 temp(this, e);
12 }
13 }
14
15 public void FileDownload(string url)
16 {
17 int percent = 0;
18 while(percent <= 100)
19 {
20 //模拟下载文件
21 ++percent;
22 DownLoadEventArgs e = new DownLoadEventArgs(percent);
23 OnFileDownloaded(e); //事件触发,向订阅者发送消息(下载百分比的值)
24
25 Thread.Sleep(1000);
26 }
27 }
28 }
三、客户端订阅事件
在客户端实例化文件下载类,然后绑定事件,如下:
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 FileManager manager = new FileManager();
6 manager.DownLoad += Manager_DownLoad; //订阅事件
7 manager.FileDownload("http://asdfwqerqasdfs.zip"); //下载文件
8 }
9
10 /// <summary>
11 /// 接到事件通知后要执行的方法
12 /// </summary>
13 /// <param name="sender">事件触发对象</param>
14 /// <param name="e">事件发送过来的消息(百分比)</param>
15 private static void Manager_DownLoad(object sender, DownLoadEventArgs e)
16 {
17 Console.WriteLine(string.Format("文件已下载:{0}%", e.Percent.ToString()));
18 }
19 }
四、显示结果
五、图示
六、个人理解
其实事件就是用将一系列订阅方法绑定在一个委托上,当方法执行时,触发到该事件时,就会按通知绑定在委托上的方法去执行。
总结
最新文章
- PostgreSQL installations
- myfocus官方网站已经挂掉,相关下载已经从googlecode转到网盘
- 安装CocoaPods报错 - [!] The dependency `AFNetworking (~>; 3.1.0)` is not used in any concrete target.
- wireshark使用简介
- WCF4.0 –- RESTful WCF Services (1) (入门)
- LR之错误处理
- OpenJudge/Poj 2105 IP Address
- java 基础知识
- servlet三种实现方式之二继承GenericServlet开发
- 由于IPv6导致的iOS应用发布失败,是否该怪Azure?
- C# 对xml进行操作
- Angular 5和ASP.NET Core入门
- Web Magic设计思想
- 第3章 PCI总线的数据交换
- Spark源码剖析 - SparkContext的初始化(六)_创建和启动DAGScheduler
- 905. Sort Array By Parity
- nginx从http跳转到https
- python3.7 contextvars在asyncio使用的
- AspNetCore MVC + Vue.Js 项目搭建
- Windows补丁更新Tips