委派 是一種**型別安全的函式指標**,封裝方法簽章 (參數、回傳型別)。允許將方法作為參數傳遞、儲存於變數、動態決定執行邏輯。是事件、LINQ、非同步程式設計的基石。
// 1. 宣告委派型別 (簽章:double, double -> double)
public delegate double BinaryOp(double x, double y);
// 2. 符合簽章的目標方法
public static double Multiply(double x, double y) => x * y;
public static double Divide(double x, double y) => y != 0 ? x / y : double.NaN;
// 3. 實例化委派、指派方法、呼叫
BinaryOp op = Multiply; // 直接指派方法群組
double result = op(3, 4); // 呼叫如同一般方法:12
op = Divide; // 動態切換行為
result = op(10, 2); // 5
using System;
delegate double BinaryOp(double x, double y);
class Program
{
static double Multiply(double x, double y) => x * y;
static double Divide(double x, double y) => y != 0 ? x / y : double.NaN;
static void Main()
{
Console.Write("輸入兩個數字 (以逗號分隔): ");
string input = Console.ReadLine();
var parts = input.Split(',');
double a = double.Parse(parts[0].Trim());
double b = double.Parse(parts[1].Trim());
Console.Write("選擇運算 (M=乘法, D=除法): ");
string choice = Console.ReadLine().Trim().ToUpper();
BinaryOp operation = (choice == "M") ? Multiply : Divide;
Console.WriteLine($"結果: {operation(a, b)}");
Console.ReadKey();
}
}
BinaryOp ops = Multiply;
ops += Divide; // 串聯
ops += (x, y) => x + y; // 加入 Lambda
foreach (BinaryOp single in ops.GetInvocationList())
{
Console.WriteLine(single(2, 3)); // 依序輸出 6, 0.666..., 5
}
// 匿名方法 (C# 2.0)
BinaryOp op1 = delegate(double x, double y) { return x % y; };
// Lambda 表達式 (C# 3.0+)
BinaryOp op2 = (x, y) => x * y; // 運算式主體
BinaryOp op3 = (x, y) => { return x / y; }; // 區塊主體
| 委派 | 簽章 | 用途 |
|---|---|---|
Action | `void ()` | 無參無回傳 |
Action<T> | `void (T)` | 單參無回傳 |
Action<T1,T2,...> | `void (T1,T2,...)` | 多參無回傳 (最多 16 參) |
Func<TResult> | `TResult ()` | 無參有回傳 |
Func<T, TResult> | `TResult (T)` | 單參有回傳 |
Func<T1,T2,TResult> | `TResult (T1,T2)` | 雙參有回傳 (最多 16 參) |
Predicate<T> | `bool (T)` | 條件判斷 |
上述範例可改寫為:`Func
委派是 C# **函式式程式設計**的入口。掌握「宣告 → 實例化 → 指派 → 呼叫」四步驟,善用 `Func`/`Action` 內建委派與 Lambda 表達式,即可寫出彈性、可測試、符合開放封閉原則的程式碼。