我正在尝试编写一个函数,其中一个参数是另一个函数——这是我以前做过很多次的任务。下面的代码可以正常工作:
int RunFunction(Func<int,int> f, int input) {
return f(input);
}
int Double(int x) {
return x*2;
}
// somewhere else in code
RunFunction(Double,5);
然而,这并不起作用:
public static class FunctionyStuff {
public static int RunFunction(this Func<int,int> f, int input) {
return f(input);
}
}
// somewhere else in code
Double.RunFunction(5);
有什么想法,为什么第一个有效而第二个无效?
Func<int, int>
和一个假设的MyIntIntDelegate
可能具有相同的签名,但是它们是不同的类型,所以编译器无法知道应该转换哪一个。 - TimwiMethod
到Func
有一个隐式转换吗? - Joenew Func<int, int>(x => 2*x).MyExtensionMethod()
,以演示必须先从lambda转换为委托类型。 - Timwi