筆記 .NET Base Class Library 各式基礎函式庫的使用原理與技巧,讓開發 .NET 程式自然且流暢 🙂

Delegate
delegate int Delegator (int x);
static void Main()
{
Delegator d = Square;
int result = d(3); // 9
}
static int Square (int x) => x * x;
也可以使用 Invoke
的方式使用 Delegate:
Delegator d = new Delegator(Square);
d.Invoke(3);
Delegate 可以在 Runtime 重新指向符合 Signature (Return & Parameters Type) 的方法:
d = Cube;
int reulst d(3); // 27
static int Cube(int x) => x * x * x;
Multicatst
翻譯是多播,使用上可以在 Delegate 變數註冊多個方法,Delegate 會依序執行被註冊的方法。
delegate void Delegator();
static void Main()
{
Delegator d = null;
d += SayHi();
d += SayBye();
d();
}
static void SayHi() { Console.WriteLine("Hello World."); }
static void SayBye() { Console.WriteLine("Bye Bye."); }
Delegate 經常與 Interface 的 Polymorphism 進行比較,而多播的特性以及