委派如同「委託他人辦事」:定義一種**方法簽名相容的型別**,實例化後可指向任何符合簽名的方法,調用時如同直接呼叫該方法。委派是型別安全的函式指標,也是「函式的類別」。
// 1. 宣告委派型別
public delegate void PrintHandler(string str);
// 2. 目標類別與方法
public class PrintStr {
public void CallPrint(string input) {
Console.WriteLine(input);
}
}
// 3. 使用
static void Main() {
PrintStr printer = new PrintStr();
PrintHandler handler = null;
// 串聯 (多播委派)
handler += new PrintHandler(printer.CallPrint);
// 調用
if (handler != null) handler("Hello World!"); // 輸出: Hello World!
// 移除
handler -= new PrintHandler(printer.CallPrint);
if (handler == null) Console.WriteLine("handler==null");
}
+= 串聯多個方法,調用時依序執行。event 關鍵字限制委派只能在類別內部觸發,外部只能 +=/-= 訂閱/退訂。