顧名思義,匿名方法是沒有名稱的方法??梢允褂梦?delegate)關(guān)鍵字定義C#中的匿名方法,并且可以將其分配給委托(delegate)類型的變量。
在匿名方法中您不需要指定返回類型,它是從方法主體內(nèi)的 return 語句推斷的。
public delegate void Print(int value); static void Main(string[] args) { Print print = delegate(int val) { Console.WriteLine("匿名方法內(nèi)部。值: {0}", val); }; print(100); }
匿名方法內(nèi)部。值:100
匿名方法可以訪問外部函數(shù)中定義的變量。
public delegate void Print(int value); static void Main(string[] args) { int i = 10; Print prnt = delegate(int val) { val += i; Console.WriteLine("匿名方法: {0}", val); }; prnt(100); }
匿名方法:110
也可以將匿名方法傳遞給接受委托作為參數(shù)的方法。
在下面的示例中,PrintHelperMethod()采用Print委托的第一個(gè)參數(shù):
public delegate void Print(int value); class Program { public static void PrintHelperMethod(Print printDel,int val) { val += 10; printDel(val); } static void Main(string[] args) { PrintHelperMethod(delegate(int val) { Console.WriteLine("匿名方法: {0}", val); }, 100); } }
匿名方法:110
saveButton.Click += delegate(Object o, EventArgs e) { System.Windows.Forms.MessageBox.Show("Save Successfully!"); };
C#3.0引入了 lambda 表達(dá)式,該表達(dá)式也像匿名方法一樣工作。
它不能包含跳轉(zhuǎn)語句,如goto,break或continue。
它不能訪問外部方法的ref 或 out參數(shù)。
它不能擁有或訪問不安全的代碼。
不能在is運(yùn)算符的左側(cè)使用。
可以使用 delegate 關(guān)鍵字定義匿名方法
匿名方法必須分配給委托。
匿名方法可以訪問外部變量或函數(shù)。
匿名方法可以作為參數(shù)傳遞。
匿名方法可用作事件處理程序。