我們已經(jīng)提到過,委托是用于引用與其具有相同標簽的方法。換句話說,您可以使用委托對象調(diào)用可由委托引用的方法。
匿名方法(Anonymous methods) 提供了一種傳遞代碼塊作為委托參數(shù)的技術。匿名方法是沒有名稱只有主體的方法。
在匿名方法中您不需要指定返回類型,它是從方法主體內(nèi)的 return 語句推斷的。
編寫匿名方法的語法
匿名方法是通過使用 delegate 關鍵字創(chuàng)建委托實例來聲明的。例如:
delegate void NumberChanger(int n); ... NumberChanger nc = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); };
代碼塊 Console.WriteLine("Anonymous Method: {0}", x); 是匿名方法的主體。
委托可以通過匿名方法調(diào)用,也可以通過命名方法調(diào)用,即,通過向委托對象傳遞方法參數(shù)。
例如:
nc(10);
實例
下面的實例演示了匿名方法的概念:
using System; delegate void NumberChanger(int n); namespace DelegateAppl { class TestDelegate { static int num = 10; public static void AddNum(int p) { num += p; Console.WriteLine("Named Method: {0}", num); } public static void MultNum(int q) { num *= q; Console.WriteLine("Named Method: {0}", num); } public static int getNum() { return num; } static void Main(string[] args) { // 使用匿名方法創(chuàng)建委托實例 NumberChanger nc = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); }; // 使用匿名方法調(diào)用委托 nc(10); // 使用命名方法實例化委托 nc = new NumberChanger(AddNum); // 使用命名方法調(diào)用委托 nc(5); // 使用另一個命名方法實例化委托 nc = new NumberChanger(MultNum); // 使用命名方法調(diào)用委托 nc(2); Console.ReadKey(); } } }
當上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結果:
Anonymous Method: 10 Named Method: 15 Named Method: 30