本質上,委託是指向若干方法的型別安全的對象(類似c++函數指標)。一個委託維持有三項重要的資訊:1,它要調用的方法的地址 2,方法的參數(如果有的話)3,方法的傳回值(如果有的話)。和c++函數指標不同的是,.net 委託可以指向靜態方法和執行個體方法。
首先來看看如何定義一個委託(使用關鍵字delegate)
- // 這個委託可以指向任何接收兩個int參數並返回int值的方法
- //二元操作
- public delegate int BinaryOp(int x, int y);
你在聲明這個BinaryOp委託的時候,編譯器會為你產生這樣的一個類:
- sealed class BinaryOp : System.MulticastDelegate
- {
- public BinaryOp(object target, uint functionAddress);
- public int Invoke(int x, int y);
- public IAsyncResult BeginInvoke(int x, int y,
- AsyncCallback cb, object state);
- public int EndInvoke(IAsyncResult result);
- }
其中,Invoke是核心方法,顧名思義,是用來調用委託中維持的每個方法。BeginInvoke() 和EndInvoke()用來非同步呼叫當前的方法。這個需要你有多線程編程的背景,超出了本文要描述的範圍。這裡你只要理解委託其實暗中實現了本來要用多線程才能實現的功能。
待續……
初次認識委託,可能會覺得有點困惑。現在來看看一個完整的例子:
- namespace SimpleDelegate
- {
- // 這個委託可以指向任何接收兩個int參數並返回int值的方法
- //二元操作
- public delegate int BinaryOp(int x, int y);
- // 該類包含BinaryOp要指向的方法
- //
- public class SimpleMath
- {
- public static int Add(int x, int y)
- { return x + y; }
- public static int Subtract(int x, int y)
- { return x - y; }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("***** Simple Delegate Example *****\n");
- // 建立一個指向SimpleMath.Add()的BinaryOp對象
- //
- BinaryOp b = new BinaryOp(SimpleMath.Add);
- // 調用Add()方法 ,間接 使用了delegate 對象.
- Console.WriteLine("10 + 10 is {0}", b(10, 10));
- Console.ReadLine();
- }
- }
- }