次のように C# でメソッドを定義する方法が必要です。
public String myMethod(Function f1,Function f2)
{
//code
}
f1 を次のようにします。
public String f1(String s1, String s2)
{
//code
}
これを行う方法はありますか?
Func<T1, T2, TResult>
確かにデリゲートを使用できます:
public String myMethod(
Func<string, string, string> f1,
Func<string, string, string> f2)
{
//code
}
このデリゲートは、2 つの文字列パラメーターを受け取り、文字列を返す関数を定義します。さまざまな数のパラメーターを取る関数を定義するための多くのいとこがあります。myMethod
別のメソッドで呼び出すには、メソッドの名前を渡すだけです。次に例を示します。
public String doSomething(String s1, String s2) { ... }
public String doSomethingElse(String s1, String s2) { ... }
public String myMethod(
Func<string, string, string> f1,
Func<string, string, string> f2)
{
//code
string result1 = f1("foo", "bar");
string result2 = f2("bar", "baz");
//code
}
...
myMethod(doSomething, doSomethingElse);
もちろん、 のパラメーターと戻り値の型f2
がまったく同じでない場合は、それに応じてメソッド シグネチャを調整する必要があります。