C#泛型方法解析因模棱两可的调用错误而失败 [英] C# generic method resolution fails with an ambiguous call error

查看:76
本文介绍了C#泛型方法解析因模棱两可的调用错误而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然后当我写new Foo().Frob();时出现错误

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?

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

This happens in VS2015 Update 3 and VS2017 RC.

这里的想法是拥有可用于类层次结构的流利的API:

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

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

推荐答案

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

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.

这篇关于C#泛型方法解析因模棱两可的调用错误而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆