概述
今天用來演示事件的例子是模擬實現一個文件下載類,在這個類中我將定義一個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 }
四、顯示結果
五、圖示
六、個人理解
其實事件就是用將一系列訂閱方法綁定在一個委托上,當方法執行時,觸發到該事件時,就會按通知綁定在委托上的方法去執行。
總結
寫博客不容易,尤其是對我這樣的c#新人,如果大家覺得寫的還好,請推薦或打賞支持,我會更加努力寫文章的。