匿名方法是在初始化委托時內聯聲明的方法。
例如下面這兩個例子:
不使用匿名方法的委托:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication7 { class Program { public static int add(int x) { return x + 20; } delegate int otherdel(int param); public static void Main() { otherdel del = add; Console.WriteLine("{0}", del(20)); Console.WriteLine("{0}", del(10)); } } }
使用匿名方法的委托:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication7 { class Program { delegate int otherdel(int param); public static void Main() { otherdel del = delegate(int x) { return x + 20; }; Console.WriteLine("{0}", del(20)); Console.WriteLine("{0}", del(10)); } } }
兩種結果是一樣的。
使用匿名方法
1)聲明委托變量時候作為初始化表達式。
2)組合委托時在賦值語句的右邊。
3)為委托增加事件時在賦值語句的右邊。
匿名方法語法
delegate (parameters ){implementationcode};
關鍵字 參數 語句塊
匿名方法不會聲明返回值類型。但是匿名方法返回值類型必須和委托返回值一樣。
參數:參數數量,類型和修飾符必須和委托一樣。
但是我們可以使圓括號為空,或省略圓括號來簡化匿名方法的參數列表。但是僅在下面兩項都為真的情況下才可以這么做。
1,委托的參數列表不包含任何out參數的委托。
2,匿名方法不使用任何參數。
例如下面:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication7 { class Program { delegate int otherdel(int param); public static void Main() { otherdel del = delegate { cleanup(); printMessage(); }; } } }
params參數:
如果委托參數包含params參數,那么params關鍵字就會被匿名方法的參數列表忽略。如下:
delegate int otherdel(int x,params int y); otherdel del = delegate(int x,int y) { ------------- };