委派是型別安全的函式指標,封裝「具有相同簽名的一或多個方法」。宣告即定義一種新型別:
public delegate int Handler(int x, int y);
Invoke() 或直接像方法一樣呼叫Handler h = new Handler(obj.Add);
Handler h = obj.Add; // 隱式 new Handler
| 委派 | 回傳值 | 參數上限 | 適用場景 |
|---|---|---|---|
Func<T1, T2, TResult> | 有 | 16 | 通用函式 |
Action<T1, T2> | 無 | 16 | 副作用操作 |
Predicate<T> | bool | 1 | 篩選條件 |
Func<int, int, int> add = (x, y) => x + y;
Action<string> log = s => Console.WriteLine(s);
Func<int, int, int> sub = delegate(int x, int y) { return x - y; };
Func<int, int, int> mul = (x, y) => x * y; // 型別推論、極致精簡
委派可透過 += 串聯多個方法,形成 MulticastDelegate:
Action<int, int> chain = (x, y) => Console.WriteLine($"Sum: {x + y}");
chain += (x, y) => Console.WriteLine($"Diff: {x - y}");
chain(10, 5); // 依序執行兩個方法
// 列舉鏈中所有方法
foreach (var d in chain.GetInvocationList())
Console.WriteLine(d.Method.Name);
注意: 有回傳值的委派鏈,最終回傳值為最後一個方法的結果。
事件本質是 private 委派欄位 + add/remove 存取器,防止外部直接呼叫或清空訂閱清單。
EventHandler 尾綴)event 關鍵字protected virtual void OnXxx(EventArgs e) 引發方法+= 註冊,-= 移除// 1. 委派
public delegate void CalcEventHandler(object sender, CalcEventArgs e);
// 2. 事件
public event CalcEventHandler Calc;
// 3. 引發
protected virtual void OnCalc(CalcEventArgs e)
{
Calc?.Invoke(this, e);
}
// 4. 參數類別
public class CalcEventArgs : EventArgs
{
public int X { get; }
public int Y { get; }
public CalcEventArgs(int x, int y) { X = x; Y = y; }
}
private CalcEventHandler calc; (委派欄位)add_Calc / remove_Calc (存取器,對應 +=/-=)calc.Invoke(),只能透過 OnCalc 間接引發。BeginInvoke / EndInvoke 非同步呼叫 (APM 模式)Task.Run / async-await 現代非同步替代方案委派是 C# 函式式程式設計的基石,掌握 Func/Action、Lambda、委派鏈 與 事件封裝,能寫出更具彈性、可測試且符合 SOLID 原則的程式碼。