工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> C言語

C# - 匿名メソッド

デリゲートは、デリゲートと同じシグネチャを持つメソッドを参照するために使用されることを説明しました。つまり、そのデリゲート オブジェクトを使用して、デリゲートが参照できるメソッドを呼び出すことができます。

匿名メソッド コード ブロックをデリゲート パラメーターとして渡す手法を提供します。匿名メソッドは、名前がなく、本体だけのメソッドです。

匿名メソッドで戻り値の型を指定する必要はありません。メソッド本体内の return ステートメントから推測されます。

匿名メソッドの記述

匿名メソッドは、デリゲート を使用してデリゲート インスタンスを作成することで宣言されます。 キーワード。たとえば、

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

C言語

  1. C# の抽象クラスとメソッド
  2. C# 部分クラスと部分メソッド
  3. C# の封印されたクラスとメソッド
  4. C# メソッドのオーバーロード
  5. Python 匿名/Lambda 関数
  6. Java匿名クラス
  7. Java 8 - デフォルトのメソッド
  8. C# - メソッド
  9. C# - デリゲート
  10. EPAメソッド21とは何ですか?
  11. 加工でワーク精度を得る一般的な方法 (2)