
- C# 基礎教程
- C# - 首頁
- C# - 概述
- C# - 環境
- C# - 程式結構
- C# - 基本語法
- C# - 資料型別
- C# - 型別轉換
- C# - 變數
- C# - 常量
- C# - 運算子
- C# - 決策制定
- C# - 迴圈
- C# - 封裝
- C# - 方法
- C# - 可空型別
- C# - 陣列
- C# - 字串
- C# - 結構體
- C# - 列舉
- C# - 類
- C# - 繼承
- C# - 多型
- C# - 運算子過載
- C# - 介面
- C# - 名稱空間
- C# - 預處理器指令
- C# - 正則表示式
- C# - 異常處理
- C# - 檔案 I/O
C# - 匿名方法
我們討論過委託用於引用任何與委託簽名相同的任何方法。換句話說,您可以使用該委託物件呼叫可以由委託引用的方法。
匿名方法提供了一種將程式碼塊作為委託引數傳遞的技術。匿名方法是沒有名稱的方法,只有主體。
您無需在匿名方法中指定返回型別;它從方法體內的 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); } public static int getNum() { return num; } static void Main(string[] args) { //create delegate instances using anonymous method NumberChanger nc = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); }; //calling the delegate using the anonymous method nc(10); //instantiating the delegate using the named methods nc = new NumberChanger(AddNum); //calling the delegate using the named methods nc(5); //instantiating the delegate using another named methods nc = new NumberChanger(MultNum); //calling the delegate using the named methods nc(2); Console.ReadKey(); } } }
當以上程式碼編譯並執行時,會產生以下結果 -
Anonymous Method: 10 Named Method: 15 Named Method: 30
廣告