加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#泛型方法解决失败并带有不明确的调用错误

发布时间:2020-12-15 17:36:00 所属栏目:百科 来源:网络整理
导读:假设我已经定义了两个不相关的类型和两个具有相同签名但不同类型过滤器的扩展方法: public class Foo {}public class Bar {}public static class FooExtensions{ public static TFoo FrobTFoo(this TFoo foo) where TFoo : Foo { } public static TFoo Brob
假设我已经定义了两个不相关的类型和两个具有相同签名但不同类型过滤器的扩展方法:
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 { }
}

那么当我写新的Foo()时,Frob();我收到一个错误

错误CS0121:以下方法或属性之间的调用是模糊的:’FooExtensions.Frob< TFoo>(TFoo)’和’BarExtensions.Frob< TBar>(TBar)

有人可以解释为什么这不成功,怎么避免呢?

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

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

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

解决方法

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

您可以阅读更多关于这个问题here.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读