Csharp-anonymous-methods

提供:Dev Guides
移動先:案内検索

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