C#のラムダ式で静的メソッドを呼び出す方法は?
静的メソッドを呼び出す場合は、ラムダ式の静的メソッド参照を使用できます。静的メソッド参照は、クラス名とメソッド名を二重コロン(::)で分けて使用します。次のようになります:
ClassName::StaticMethodName
以下は、ラムダ式で静的メソッドを呼び出す方法を示す例です。
using System;
public class Program
{
public static void Main()
{
Func<int, int, int> add = Calculator.Add;
int result = add(5, 3);
Console.WriteLine(result);
}
}
public static class Calculator
{
public static int Add(int a, int b)
{
return a + b;
}
}
上記の例では、私たちはラムダ式で静的メソッド参照Calculator.Addを使用して静的メソッドを呼び出しました。その後、そのラムダ式をFunc<int、int、int>デリゲートに割り当て、パラメータ5と3を渡して静的メソッドを実行しました。最後に、結果をコンソールに出力しました。
結果は8です。