C# 将函数作为参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18176856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing a function as parameter
提问by Babak.Abad
I need a way to define a method in c# like this:
我需要一种在 c# 中定义方法的方法,如下所示:
public String myMethod(Function f1,Function f2)
{
//code
}
Let f1 is:
让 f1 是:
public String f1(String s1, String s2)
{
//code
}
is there any way to do this?
有没有办法做到这一点?
采纳答案by p.s.w.g
Sure you can use the Func<T1, T2, TResult>
delegate:
当然你可以使用Func<T1, T2, TResult>
委托:
public String myMethod(
Func<string, string, string> f1,
Func<string, string, string> f2)
{
//code
}
This delegate defines a function which takes two string parameters and return a string. It has numerous cousins to define functions which take different numbers of parameters. To call myMethod
with another method, you can simply pass in the name of the method, for example:
这个委托定义了一个函数,它接受两个字符串参数并返回一个字符串。它有许多类似的方法来定义采用不同数量参数的函数。要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);
Of course, if the parameter and return types of f2
aren't exactly the same, you may need to adjust the method signature accordingly.
当然,如果 的参数和返回类型f2
不完全相同,您可能需要相应地调整方法签名。