C#泛型方法解析失败,出现模糊的调用错误

Rom*_*ter 11 c# extension-methods type-inference type-resolution

假设我已经定义了两个不相关的类型和两个具有相同签名但不同类型过滤器的扩展方法:

public class Foo {}
public class Bar {}

public static class FooExtensions
{
    public static TFoo Frob<TFoo>(this TFoo foo) where TFoo : Foo { }
    public static TFoo Brob<TFoo>(this TFoo foo) where TFoo : Foo { }
}

public static class BarExtensions
{
    public static TBar Frob<TBar>(this TBar bar) where TBar : Bar { }
}
Run Code Online (Sandbox Code Playgroud)

然后,当我写作时,new Foo().Frob();我得到一个错误

error CS0121: The call is ambiguous between the following methods or properties: 'FooExtensions.Frob<TFoo>(TFoo)' and 'BarExtensions.Frob<TBar>(TBar)'

有人可以解释为什么这会失败以及如何避免它?

编辑:这发生在VS2015 Update 3和VS2017 RC中.

EDIT2:这里的想法是拥有适用于类层次结构的流畅API:

new Foo()
  .Frob()
  .Brob()
Run Code Online (Sandbox Code Playgroud)

InB*_*een 11

泛型类型参数的约束不是方法签名的一部分.从分辨率的角度来看,这两种方法基本相同; 当编译器尝试解析调用时,它会看到两个有效的方法,并且无法选择更好的方法,因此调用被标记为不明确.

您可以在此处详细了解此问题.

  • @EricLippert非常感谢你,很难夸大我对这门语言的了解,以及一般的编程,阅读你的博客. (3认同)