委派 是一種 參考型別,封裝了對「符合特定簽章之方法」的引用。它類似 C++ 的函式指標或 Delphi 的方法指標,但具備型別安全、支援多播與非同步呼叫等 .NET 特有能力。
| 語言 | 對應機制 | 語法範例 |
|---|---|---|
| C++ | 函式指標 | typedef int (*GetNum)(double rNum); |
| Delphi | 方法指標 | function GetNum(rNum: Real): Integer; |
| C# | 委派 | delegate string Do(string command); |
C# 委派本質是繼承自 System.MulticastDelegate 的密封類別,編譯器自動產生 Invoke、BeginInvoke/EndInvoke 方法。
經典比喻:老闆(呼叫者)→ 秘書(委派)→ 員工(實作者)。老闆只對秘書下達指令,不需知道具體由哪位員工執行,秘書依指令內容動態決定派遣對象。
// 1. 宣告委派型別
public delegate string Do(string command);
// 2. 實作者:市場專員
public class MarketMan
{
public string GetMarketInfo(string cmd) => $"市場報告:{cmd}";
}
// 3. 實作者:生產專員(靜態方法同樣適用)
public class ProductMan
{
public static string ProduceProduct(string cmd) => $"生產紀錄:{cmd}";
}
// 4. 秘書類別:持有委派並決定派遣邏輯
public class Secretary
{
public Do DoIt { get; set; }
public void ExecuteCommand(string command)
{
// 依指令內容動態綁定實作方法
if (command.Contains("市場"))
DoIt = new Do(new MarketMan().GetMarketInfo); // 實例方法
else if (command.Contains("生產"))
DoIt = new Do(ProductMan.ProduceProduct); // 靜態方法
else
DoIt = cmd => "無對應處理人員";
Console.WriteLine(DoIt(command)); // 呼叫委派
}
}
// 5. 老闆:只需新增秘書並下達指令
public class Boss
{
public static void Main()
{
var secretary = new Secretary();
secretary.ExecuteCommand("調研市場趨勢");
secretary.ExecuteCommand("生產氫彈");
}
}
Do multi = null;
multi += new Do(obj1.MethodA);
multi += new Do(obj2.MethodB);
multi("cmd"); // 依序呼叫 MethodA、MethodB,回傳值為最後一個方法的結果
Do d = delegate(string s) { return s.ToUpper(); };
Do d2 = s => s.ToLower();
Func<T, TResult>:有回傳值。Action<T>:無回傳值。Predicate<T>:回傳 bool。現代 C# 建議優先使用 Func/Action 減少自訂委派宣告。
委派是 C# 事件模型、LINQ、非同步程式、策略模式等核心基石。掌握「宣告、實例化、多播、型別推論」四大關鍵,即能靈活實現鬆耦合、可擴充的架構設計。