回調函數廣泛用於排序、視窗程序、鉤子、非同步呼叫等場景。C/C++ 函數指標僅為記憶體位址,缺乏參數型別、回傳型別、呼叫慣例等資訊,非型別安全。.NET 引入委派,提供型別安全的回調機制。
// 定義委派型別(簽章:Object, int, int -> void)
public delegate void Feedback(Object value, int item, int numItems);
// 使用委派型別的方法
public void ProcessItems(Feedback feedback) {
for (int i = 0; i < items.Length; i++) {
if (feedback != null)
feedback(items[i], i + 1, items.Length);
}
}
委派本質是方法包裝器,封裝方法參考與目標物件(實例方法時)。
static void FeedbackToConsole(Object value, int item, int numItems) {
Console.WriteLine("Processing item {0} of {1}: {2}.", item, numItems, value);
}
static void FeedbackToMsgBox(Object value, int item, int numItems) {
MessageBox.Show(String.Format("Processing item {0} of {1}: {2}.", item, numItems, value));
}
// 單一委派
set.ProcessItems(new Set.Feedback(FeedbackToConsole));
// 委派鏈結(多播委派)
Set.Feedback fb = null;
fb += new Set.Feedback(FeedbackToConsole);
fb += new Set.Feedback(FeedbackToMsgBox);
set.ProcessItems(fb); // 依序呼叫兩個方法
關鍵點:
+=/-= 操作符建立/移除委派鏈結節點。委派實例方法時,隱含捕獲目標物件參考(this)。
public void FeedbackToFile(Object value, int item, int numItems) {
using (StreamWriter sw = new StreamWriter("Status", true)) {
sw.WriteLine("Processing item {0} of {1}: {2}.", item, numItems, value);
}
}
// 使用實例方法
App appObj = new App();
set.ProcessItems(new Set.Feedback(appObj.FeedbackToFile));
實例方法委派內部持有目標物件參考,防止過早被垃圾收集。
Method:目標方法的 MethodInfo。Target:目標物件參考(靜態方法為 null)。InvocationList:多播委派的委派陣列。委派是 .NET 型別安全回調的基石,支援靜態/實例方法、多播鏈結、編譯期簽章驗證。理解委派內部結構與鏈結呼叫機制,是掌握事件模型、非同步程式設計、LINQ 等進階特性的前提。