在 2.0 之前的 C# 版本中,聲明委託的唯一方法是使用命名方法。C# 2.0 引入了匿名方法,而在 C# 3.0 及更高版本中,Lambda 運算式取代了匿名方法,作為編寫內聯代碼的首選方式。不過,本主題中有關匿名方法的資訊同樣也適用於 Lambda 運算式。有一種情況下,匿名方法提供了 Lambda 運算式中所沒有的功能。匿名方法使您能夠省略參數列表,這意味著可以將匿名方法轉換為帶有各種簽名的委託。這對於 Lambda 運算式來說是不可能的。匿名方法由關鍵字delegate、可選的參數列表和包含在 { 和 } 分隔字元中的語句列表組成。如果匿名方法沒有使用委託提供的參數,因此可以省略參數列表。若要獲得對參數的訪問,該匿名方法需要參數列表。
namespace Test
{
public partial class lambda : System.Web.UI.Page
{
delegate int Del(int x, int y);
protected void Page_Load(object sender, EventArgs e)
{
//Instantiate the delegate type with an anonymous method. The result: 5
Del d = delegate(int m, int n) { return m + n; };
Response.Write(d(3, 2));
//Instantiate the deledate type with a named method "add". The result: 9
//Also can write like this: d = add;
d = new Del(add);
Response.Write(d(4, 5));//result: 9
//No parameter delegate
this.Button1.Click += delegate { Response.Write("No parameter delegate!"); };
}
private int add(int m,int n)
{
return m + n;
}
}
}