前面我們學(xué)習(xí)過(guò),委托可用于引用任何與委托簽名相同的方法。換句話(huà)說(shuō),可以調(diào)用可以由委托使用該委托對(duì)象引用的方法。
匿名方法提供了一種將代碼塊作為委托參數(shù)傳遞的技術(shù)。匿名方法是沒(méi)有名稱(chēng)的方法,只有方法體。
不需要在匿名方法中指定返回類(lèi)型; 它是從方法體中的return語(yǔ)句來(lái)推斷的。
使用delegate關(guān)鍵字創(chuàng)建代理實(shí)例時(shí),就可以聲明匿名方法。 例如,
delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
代碼塊Console.WriteLine("Anonymous Method: {0}", x);是匿名方法體。
代理可以使用匿名方法和命名方法以相同的方式調(diào)用,即通過(guò)將方法參數(shù)傳遞給委托對(duì)象。
例如,
nc(10);
以下示例演示如何實(shí)現(xiàn)概念:
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)
{
//create delegate instances using anonymous method
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
//calling the delegate using the anonymous method
nc(10);
//instantiating the delegate using the named methods
nc = new NumberChanger(AddNum);
//calling the delegate using the named methods
nc(5);
//instantiating the delegate using another named methods
nc = new NumberChanger(MultNum);
//calling the delegate using the named methods
nc(2);
Console.ReadKey();
}
}
}
當(dāng)上述代碼被編譯并執(zhí)行時(shí),它產(chǎn)生以下結(jié)果:
Anonymous Method: 10
Named Method: 15
Named Method: 30