C# generic method resolution fails with an ambiguous call error

送分小仙女□ 提交于 2019-12-04 18:03:46

问题


Suppose I have defined two unrelated types and two extension methods with the same signature but different type filters:

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 { }
}

Then when I write new Foo().Frob(); I get an error

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

Could someone explain why this fails and how to avoid it?

EDIT: This happens in VS2015 Update 3 and VS2017 RC.

EDIT2: The idea here is to have fluent API that works on a class hierarchy:

new Foo()
  .Frob()
  .Brob()

回答1:


The constraint of a generic type parameter is not part of the method's signature. These two methods are essentially the same from a resolution point of view; when the compiler tries to resolve the call it sees two valid methods and it has no way to choose the better one, therefore the call is flagged as ambiguous.

You can read more about this issue here.



来源:https://stackoverflow.com/questions/42078610/c-sharp-generic-method-resolution-fails-with-an-ambiguous-call-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!