我已经定义了这些方法重载,只有Action / Func参数不同:
public void DoSomethingWithValues(Action<decimal, decimal> d, decimal x, decimal y)
{
d(x, y);
}
public void DoSomethingWithValues(Func<decimal, decimal, decimal> d, decimal x, decimal y)
{
var value = d(x, y);
}
我尝试通过内联lambda,Func&lt;&gt;和方法调用它们:
public Func<decimal, decimal, decimal> ImAFuncWhichDoesSomething = (x, y) => (x + y) / 5;
public decimal ImAMethodWhichDoesSomething(decimal x, decimal y)
{
return (x + y + 17) / 12;
}
public void DoSomething()
{
DoSomethingWithValues((x, y) => (x - y) / 17 , 1, 2); // Inline lambda compiles OK
DoSomethingWithValues(ImAFuncWhichDoesSomething, 1, 2); // Func<> compiles OK
DoSomethingWithValues(ImAMethodWhichDoesSomething, 1, 2); // Method generates "ambiguous invocation" error!!
}
前两个编译正常并按返回类型解析。
但是由于“模糊调用”错误,方法无法编译!
为什么lambda / func通过返回类型解决重载,而方法不解决?