參考資料:《CLR Via C#》第 15.4 節「委托揭秘」(第 281 頁)。
以下程式碼展示了委托的基本宣告、實例化與調用流程:
using System;
using System.Collections.Generic;
using System.Text;
namespace Delegate
{
public class DelegateTest
{
protected delegate void MyDelegate();
private void TestMethod() { }
private void Method()
{
MyDelegate aMyDelegate = new MyDelegate(TestMethod);
Method(aMyDelegate);
}
private void Method(MyDelegate aMyDelegate)
{
if (aMyDelegate != null)
{
aMyDelegate();
}
}
}
}
表面上看,委托使用起來非常直觀:用 delegate 關鍵字定義,用 new 操作符構造實例,用熟悉的方法調用語法觸發回調。但實際情況遠比這複雜——編譯器與 CLR 在幕後做了大量工作來隱藏複雜性。本文將深入剖析編譯器與 CLR 如何實現委托,助你透徹理解其運作原理,從而更高效地運用委托。
先看這行核心程式碼:
public delegate void MyDelegate();
這行看似簡單的宣告,實則啟動了編譯器的一連串代碼生成邏輯,將在下一篇中詳細拆解。