委派是 C# 函數式程式設計的基石。.NET 核心庫內建 Action、Func 系列泛型委派,涵蓋 0~16 參數,幾乎可取代所有自訂委派宣告,統一程式碼風格。
| 委派 | 回傳值 | 參數數 | 宣告範例 |
|---|---|---|---|
Action | void | 0 | delegate void Action() |
Action<T> | void | 1 | delegate void Action<T>(T arg) |
| ... | void | 2~16 | Action<T1,T2,T3...> |
Func<TResult> | TResult | 0 | delegate TResult Func<TResult>() |
Func<T,TResult> | TResult | 1 | delegate TResult Func<T,TResult>(T arg) |
| ... | TResult | 1~16 | Func<T1,T2,...,TResult> |
兩者皆繼承 MulticastDelegate,支援多播合併(+/-)。
static void Output(string s) => Console.WriteLine(s);
static int Add(int a, int b) => a + b;
var act = new Action<string>(Output);
act("Hello Action"); // 輸出: Hello Action
var func = new Func<int, int, int>(Add);
int sum = func(3, 5); // sum = 8
Console.WriteLine(sum);
Action act = s => Console.WriteLine($"Lambda: {s}");
Func func = (a, b) => a * b;
| 優點 | 缺點 |
|---|---|
| 無需宣告新委派型別,減少樣板碼 | 型別名稱無法表達業務意圖(如 EventHandler vs Action<object,EventArgs>) |
| 統一風格,易讀、易維護 | 參數超過 16 仍需自訂委派(極少見) |
| 零效能損失,編譯器同等對待 | 公開 API 建議仍用具名委派,語意更清晰 |
Expression> expr = (a, b) => a + b;
Func compiled = expr.Compile(); // 編譯為委派
// 亦可用於 LINQ to SQL、動態查詢建構
Action/Func。delegate void MyEventHandler(...))提升可讀性。