| 欄位 | 型別 | 說明 |
|---|---|---|
| _target | System.Object | 封裝靜態方法時為 null;封裝實例方法時參考調用物件(即隱式 this 參數) |
| _methodPtr | System.IntPtr | CLR 內部整數值,標識要回調的具體方法 |
| _invocationList | System.Object | 通常為 null;多播委派時參考委派陣列 |
所有委派皆有建構函式 (object target, IntPtr methodPtr)。但原始碼中寫法為:
MyDelegate d = new MyDelegate(TestMethod);
編譯器魔法:C# 編譯器識別此為委派建構,自動解析:
target 參數(靜態方法傳 null)IntPtr(從 MethodDef/MemberRef 元資料取得) → 傳給 methodPtr建構函式內部將兩參數存入 _target、_methodPtr,並將 _invocationList = null。
// 原始呼叫代碼
private void Method(MyDelegate aMyDelegate)
{
if (aMyDelegate != null) aMyDelegate();
}
編譯器轉換:看到 aMyDelegate() → 生成 aMyDelegate.Invoke() 呼叫。
Invoke 內部執行:使用 _target 與 _methodPtr 對指定物件呼叫所需方法。
每個委派物件實際封裝:一個方法 + 調用該方法時要操作的一個物件。