C/C++ 的指標雖強大但不安全(型別不匹配、記憶體錯誤)。C# 移除指標(除非 unsafe),改以委派提供類型安全的方法參考。
delegate int MyDelegate(); // 無參數、回傳 int 的方法簽章
out 參數。System.Delegate。using System;
delegate int MyDelegate();
public class MyClass {
public int InstanceMethod() {
Console.WriteLine("Call instance method.");
return 0;
}
static public int StaticMethod() {
Console.WriteLine("Call static method.");
return 0;
}
}
public class Test {
static void Main() {
MyClass p = new MyClass();
MyDelegate d = new MyDelegate(p.InstanceMethod); // 實例方法
d();
d = new MyDelegate(MyClass.StaticMethod); // 靜態方法
d();
}
}
輸出:
Call instance method.
Call static method.
實例.方法 或 類別.靜態方法。event 關鍵字基礎)Comparison<T>)Func<T, TResult>、Action<T>)