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 }

四、显示结果

五、图示

六、个人理解

其实事件就是用将一系列订阅方法绑定在一个委托上,当方法执行时,触发到该事件时,就会按通知绑定在委托上的方法去执行。

总结

最新文章

  1. PostgreSQL installations
  2. myfocus官方网站已经挂掉,相关下载已经从googlecode转到网盘
  3. 安装CocoaPods报错 - [!] The dependency `AFNetworking (~&gt; 3.1.0)` is not used in any concrete target.
  4. wireshark使用简介
  5. WCF4.0 –- RESTful WCF Services (1) (入门)
  6. LR之错误处理
  7. OpenJudge/Poj 2105 IP Address
  8. java 基础知识
  9. servlet三种实现方式之二继承GenericServlet开发
  10. 由于IPv6导致的iOS应用发布失败,是否该怪Azure?
  11. C# 对xml进行操作
  12. Angular 5和ASP.NET Core入门
  13. Web Magic设计思想
  14. 第3章 PCI总线的数据交换
  15. Spark源码剖析 - SparkContext的初始化(六)_创建和启动DAGScheduler
  16. 905. Sort Array By Parity
  17. nginx从http跳转到https
  18. python3.7 contextvars在asyncio使用的
  19. AspNetCore MVC + Vue.Js 项目搭建
  20. Windows补丁更新Tips

热门文章

  1. poj 3691
  2. 常用的shell命令整理
  3. Qt程式异常崩溃处理技巧(Win)
  4. stm32之GPIO
  5. [NOIP 2005]-- 篝火晚会
  6. 实战nginx 基础知识总结(一)1.1
  7. Android:设置背景图和标题
  8. ZOJ 3778 Talented Chef 模拟 [ 祝愿明天省赛一帆风顺, ZJSU_Bloom WILL WIN : )
  9. LOVEU
  10. Qt 5.x 全局热键 for windows