首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

.NET 委派機制深度解析(一):型別安全的回調函數

     編輯:關於C語言

從回調函數到委派

回調函數廣泛用於排序、視窗程序、鉤子、非同步呼叫等場景。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); // 依序呼叫兩個方法

關鍵點:

  • 編譯器驗證方法簽章與委派型別完全相符,否則報錯 CS0123。
  • +=/-= 操作符建立/移除委派鏈結節點。
  • 呼叫委派時自動遍歷鏈結列表,依序執行所有目標方法。

實例方法委派

委派實例方法時,隱含捕獲目標物件參考(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 等進階特性的前提。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved