new DelegateType(MethodName) 綁定目標方法。using System;
delegate int Compute(int left, int right); // 1. 宣告
class A
{
public int Mul(int x, int y) => x * y; // 實例方法
}
class Test
{
public static int Add(int x, int y) => x + y; // 靜態方法
static void Main()
{
Compute c1 = new Compute(Add); // 靜態方法實例化
A a = new A();
Compute c2 = new Compute(a.Mul); // 實例方法實例化
int r1 = c1(2, 3); // 5
int r2 = c2(2, 3); // 6
Console.WriteLine($"{r1}, {r2}");
}
}
兩個委派型別相同指名稱相同;委派實例相等指綁定相同方法鏈。型別相容需滿足:
實例化時,目標方法簽章需與委派型別相容(支援協變/逆變:C# 2.0+ 允許方法回傳型別為委派回傳型別的衍生類別,參數型別為委派參數型別的基類別)。
+/+= 組合,-/-= 移除。delegate void MyDelegate(string s);
static void Hello(string s) => Console.WriteLine($"Hello, {s}!");
static void Goodbye(string s) => Console.WriteLine($"Goodbye, {s}!");
static void Main()
{
MyDelegate a = Hello, b = Goodbye;
MyDelegate c = a + b; // Hello -> Goodbye
MyDelegate d = c - a; // 僅剩 Goodbye
a("A"); // Hello, A!
b("B"); // Goodbye, B!
c("C"); // Hello, C! -> Goodbye, C!
d("D"); // Goodbye, D!
// 進階組合/移除
MyDelegate e = a + b + a; // Hello, Goodbye, Hello
b += b; // b 變成 Goodbye, Goodbye
MyDelegate f = e - b; // 移除最後一個 Goodbye, Goodbye -> 剩 Hello, Goodbye, Hello
}
new DelegateType(...),直接指派方法群組:Compute c = Add;Func<T, TResult>、Action<T>、Predicate<T>,減少自訂委派型別。Compute c = (x, y) => x + y;EventHandler<TEventArgs>。