将函数作为参数传递

Bab*_*bad 20 c# methods

我需要一种在c#中定义方法的方法,如下所示:

public String myMethod(Function f1,Function f2)
{
    //code
}
Run Code Online (Sandbox Code Playgroud)

设f1为:

public String f1(String s1, String s2)
{
    //code
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

p.s*_*w.g 34

当然你可以使用Func<T1, T2, TResult>代表:

public String myMethod(
    Func<string, string, string> f1,
    Func<string, string, string> f2)
{
    //code
}
Run Code Online (Sandbox Code Playgroud)

该委托定义了一个函数,它接受两个字符串参数并返回一个字符串.它有许多表兄弟来定义具有不同数量参数的函数.要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);
Run Code Online (Sandbox Code Playgroud)

当然,如果参数和返回类型f2不完全相同,则可能需要相应地调整方法签名.

  • 另外:当你想执行f1和f2时,你只需要将它们称为方法.string result = f1("first","second"); (4认同)