C# 匿名方法
我們已經提到過,委託是用於引用與其具有相同標籤的方法。換句話說,您可以使用委託對象調用可由委託引用的方法。
匿名方法(Anonymous methods) 提供了一種傳遞代碼塊作為委託參數的技術。匿名方法是沒有名稱只有主體的方法。
在匿名方法中您不需要指定返回類型,它是從方法主體內的 return 語句推斷的。
編寫匿名方法的語法
匿名方法是通過使用 delegate 關鍵字創建委託實例來聲明的。例如:
delegate void NumberChanger(int n); ... NumberChanger nc = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); };
代碼塊 Console.WriteLine("Anonymous Method: {0}", x); 是匿名方法的主體。
委託可以通過匿名方法調用,也可以通過命名方法調用,即,通過向委託對象傳遞方法參數。
例如:
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);
}
static void Main(string[] args)
{
// 使用匿名方法創建委託實例
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
// 使用匿名方法調用委託
nc(10);
// 使用命名方法實例化委託
nc = new NumberChanger(AddNum);
// 使用命名方法調用委託
nc(5);
// 使用另一個命名方法實例化委託
nc = new NumberChanger(MultNum);
// 使用命名方法調用委託
nc(2);
Console.ReadKey();
}
}
}
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);
}
static void Main(string[] args)
{
// 使用匿名方法創建委託實例
NumberChanger nc = delegate(int x)
{
Console.WriteLine("Anonymous Method: {0}", x);
};
// 使用匿名方法調用委託
nc(10);
// 使用命名方法實例化委託
nc = new NumberChanger(AddNum);
// 使用命名方法調用委託
nc(5);
// 使用另一個命名方法實例化委託
nc = new NumberChanger(MultNum);
// 使用命名方法調用委託
nc(2);
Console.ReadKey();
}
}
}
當上面的代碼被編譯和執行時,它會產生下列結果:
Anonymous Method: 10 Named Method: 15 Named Method: 30