为什么第一次调用Foo
下面编译但第二个导致模棱两可的调用编译器错误?
(使用 c# 7.2)
private static void AmbiguousAsyncOverload() {
Foo(() => Bar()); // This is OK
//Foo(Bar); // Error, ambiguous overload
}
private static void Foo(Func<int> func) {
func();
}
private static void Foo(Func<string> func) {
func();
}
private static int Bar() {
return 4;
}
如果我删除 Func<int>
的第一个( Foo
)实现,因此可能存在歧义,那么编译器(正确地)报告 Bar
没有传递给 Foo
的正确签名,这意味着它有足够的信息来解决歧义。
如果编译器在重载解析期间没有查看返回值并因此两个调用都失败,我会理解,但我的问题是为什么一个调用编译正常而另一个调用没有。
最佳答案
这是一个 issue适用于所有版本的 C#,直到它在 v7.3 中得到修复。重载解析期间未考虑返回类型。来自release notes (或 language proposal )对于 C# 7.3:
- For a method group conversion, candidate methods whose return type doesn't match up with the delegate's return type are removed from the set.
关于c# - 为什么这个方法调用不明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56951289/