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
廣告