C#中Event事件的實現(xiàn)示例
什么是事件?
定義
- 事件是一種特殊的委托,用于在某一動作發(fā)生時通知其他對象。
- 它允許一個對象向多個監(jiān)聽者廣播消息。
用途
- 實現(xiàn)發(fā)布-訂閱模式,主要用于解耦對象之間的交互,不同模塊能動態(tài)響應(yīng)特定事件。
和委托關(guān)系
- 委托是事件的基礎(chǔ),它定義了事件處理器的簽名。事件是基于委托的封裝和擴展。
事件的組成部分
- 事件聲明:在類中定義事件,通常使用event關(guān)鍵字。
- 事件觸發(fā):在某個動作完成后,引發(fā)事件。
- 事件訂閱:外部對象注冊方法來響應(yīng)事件。
基本語法
1. 定義事件
public delegate void NotifyEventHandler(object sender, EventArgs e);
public class Process
{
// 使用委托類型定義事件
public event NotifyEventHandler ProcessCompleted;
public void StartProcess()
{
Console.WriteLine("Process started.");
// 模擬過程完成后引發(fā)事件
OnProcessCompleted(EventArgs.Empty);
}
protected virtual void OnProcessCompleted(EventArgs e)
{
ProcessCompleted?.Invoke(this, e);
}
}
2. 訂閱和觸發(fā)事件
public class Program
{
public static void Main()
{
Process process = new Process();
// 訂閱事件
process.ProcessCompleted += Process_ProcessCompleted;
process.StartProcess();
}
private static void Process_ProcessCompleted(object sender, EventArgs e)
{
Console.WriteLine("Process completed event received.");
}
}
說明:
- ProcessCompleted事件是在OnProcessCompleted方法中觸發(fā)的。
- Process_ProcessCompleted是事件處理器,當(dāng)事件被觸發(fā)時會被調(diào)用。
高級主題
內(nèi)置事件處理器
- EventHandler:這是C#提供的標(biāo)準(zhǔn)事件處理器委托類型,常用于無數(shù)據(jù)或簡單數(shù)據(jù)的事件:
public event EventHandler ProcessCompleted;
- EventHandler<TEventArgs>:用于傳遞附加信息:
public class CustomEventArgs : EventArgs
{
public string Message { get; set; }
}
public event EventHandler<CustomEventArgs> ProcessCompletedWithMessage;
使用內(nèi)置EventHandler
public class SimpleProcess
{
public event EventHandler ProcessCompleted;
public void CompleteProcess()
{
Console.WriteLine("Completing process...");
ProcessCompleted?.Invoke(this, EventArgs.Empty);
}
}
自定義事件參數(shù)
- 如果需要傳遞額外的數(shù)據(jù),可以創(chuàng)建自定義的事件參數(shù)類。
public class DownloadEventArgs : EventArgs
{
public string FileName { get; set; }
public long FileSize { get; set; }
}
public class DownloadManager
{
public event EventHandler<DownloadEventArgs> DownloadCompleted;
public void CompleteDownload(string fileName, long fileSize)
{
Console.WriteLine($"Download completed: {fileName}, Size: {fileSize}");
OnDownloadCompleted(new DownloadEventArgs { FileName = fileName, FileSize = fileSize });
}
protected virtual void OnDownloadCompleted(DownloadEventArgs e)
{
DownloadCompleted?.Invoke(this, e);
}
}
事件的多播特性
事件是基于委托的,因此支持多播,即多個訂閱者可以同時接收同一事件通知。
public static void HandleSuccess(object sender, EventArgs e)
{
Console.WriteLine("Success handler executed.");
}
public static void Main()
{
SimpleProcess sp = new SimpleProcess();
// 多個方法訂閱同一事件
sp.ProcessCompleted += Process_ProcessCompleted;
sp.ProcessCompleted += HandleSuccess;
sp.CompleteProcess();
}
實踐習(xí)題
1.創(chuàng)建一個類DownloadManager,定義一個DownloadCompleted事件。在下載完成后觸發(fā)此事件,并在主程序中訂閱和處理該事件。
using System;
public class DownloadManager
{
public event EventHandler DownloadCompleted;
public void StartDownload()
{
Console.WriteLine("Starting download...");
// Simulate download completion
OnDownloadCompleted(EventArgs.Empty);
}
protected virtual void OnDownloadCompleted(EventArgs e)
{
DownloadCompleted?.Invoke(this, e);
}
}
public class Program
{
public static void Main()
{
DownloadManager dm = new DownloadManager();
// 訂閱事件
dm.DownloadCompleted += Download_Completed;
dm.StartDownload();
}
private static void Download_Completed(object sender, EventArgs e)
{
Console.WriteLine("Download completed event received.");
}
}
2.修改上述DownloadManager,使得DownloadCompleted事件攜帶下載的文件名和大小信息。
using System;
public class DownloadEventArgs : EventArgs
{
public string FileName { get; set; }
public long FileSize { get; set; }
}
public class DownloadManager
{
public event EventHandler<DownloadEventArgs> DownloadCompleted;
public void StartDownload(string fileName, long fileSize)
{
Console.WriteLine($"Starting download of {fileName}...");
// Simulate download completion
OnDownloadCompleted(new DownloadEventArgs { FileName = fileName, FileSize = fileSize });
}
protected virtual void OnDownloadCompleted(DownloadEventArgs e)
{
DownloadCompleted?.Invoke(this, e);
}
}
public class Program
{
public static void Main()
{
DownloadManager dm = new DownloadManager();
// 訂閱事件
dm.DownloadCompleted += Download_Completed;
dm.StartDownload("example.txt", 1024);
}
private static void Download_Completed(object sender, DownloadEventArgs e)
{
Console.WriteLine($"Download completed: {e.FileName}, Size: {e.FileSize}");
}
}
以上內(nèi)容涵蓋了如何定義、使用和擴展事件。更多相關(guān)C# Event事件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#使用ILGenerator動態(tài)生成函數(shù)的簡單代碼
這篇文章主要介紹了C#使用ILGenerator動態(tài)生成函數(shù)的簡單代碼,需要的朋友可以參考下2017-08-08
用C#的params關(guān)鍵字實現(xiàn)方法形參個數(shù)可變示例
params關(guān)鍵字以實現(xiàn)方法形參個數(shù)可變是C#語法的一大優(yōu)點,下面是用C#中的params關(guān)鍵字實現(xiàn)方法形參個數(shù)可變2014-09-09
C#使用xsd文件驗證XML格式是否正確的實現(xiàn)方法
這篇文章主要介紹了C#使用xsd文件驗證XML格式是否正確的實現(xiàn)方法,結(jié)合實例形式分析了C#針對xml文件的創(chuàng)建、驗證相關(guān)操作技巧,需要的朋友可以參考下2017-01-01
.net中前臺javascript與后臺c#函數(shù)相互調(diào)用問題
.net中前臺javascript與后臺c#函數(shù)相互調(diào)用問題...2007-12-12

