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言語