我們已經(jīng)提到過(guò),委托是用于引用與其具有相同標(biāo)簽的方法。換句話說(shuō),您可以使用委托對(duì)象調(diào)用可由委托引用的方法。

匿名方法(Anonymous methods) 提供了一種傳遞代碼塊作為委托參數(shù)的技術(shù)。匿名方法是沒(méi)有名稱(chēng)只有主體的方法。

在匿名方法中您不需要指定返回類(lèi)型,它是從方法主體內(nèi)的 return 語(yǔ)句推斷的。

編寫(xiě)匿名方法的語(yǔ)法

匿名方法是通過(guò)使用 delegate 關(guān)鍵字創(chuàng)建委托實(shí)例來(lái)聲明的。例如:

delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x)
{
    Console.WriteLine("Anonymous Method: {0}", x);
};

代碼塊 Console.WriteLine("Anonymous Method: {0}", x); 是匿名方法的主體。

委托可以通過(guò)匿名方法調(diào)用,也可以通過(guò)命名方法調(diào)用,即,通過(guò)向委托對(duì)象傳遞方法參數(shù)。

例如:

nc(10);

實(shí)例

下面的實(shí)例演示了匿名方法的概念:

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)建委托實(shí)例
            NumberChanger nc = delegate(int x)
            {
               Console.WriteLine("Anonymous Method: {0}", x);
            };
            
            // 使用匿名方法調(diào)用委托
            nc(10);

            // 使用命名方法實(shí)例化委托
            nc =  new NumberChanger(AddNum);
            
            // 使用命名方法調(diào)用委托
            nc(5);

            // 使用另一個(gè)命名方法實(shí)例化委托
            nc =  new NumberChanger(MultNum);
            
            // 使用命名方法調(diào)用委托
            nc(2);
            Console.ReadKey();
        }
    }
}

當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:

Anonymous Method: 10
Named Method: 15
Named Method: 30