【问题标题】:Extension methods for both ICollection and IReadOnlyCollectionICollection 和 IReadOnlyCollection 的扩展方法
【发布时间】:2013-09-08 19:03:14
【问题描述】:

我想为 ICollection 和 IReadonlyCollection 接口编写一个扩展方法(例如.IsEmpty()):

public static bool IsEmpty<T>(this IReadOnlyCollection<T> collection)
{
  return collection == null || collection.Count == 0;
}

public static bool IsEmpty<T>(this ICollection<T> collection)
{
  return collection == null || collection.Count == 0;
}

但是当我将它与实现两个接口的类一起使用时,我显然得到了“模糊调用”。 我不想输入myList.IsEmpty&lt;IReadOnlyCollection&lt;myType&gt;&gt;(),我希望它只是myList.IsEmpty()

这可能吗?

【问题讨论】:

  • 您不能为IEnumerable&lt;T&gt; 设置一种方法吗?顺便说一句。在同一个类中同时实现ICollection&lt;T&gt;IReadOnlyCollection&lt;T&gt; 似乎有点奇怪。
  • 许多标准类都实现了它们。例如。 List&lt;T&gt;Dictionary&lt;T&gt;
  • 要么给它们起不同的名字,要么把它们放在不同命名空间的不同静态类中。
  • @mikez 但你不应该这样做。欢迎使用鸭子打字和 MS 错误地没有 ICollection&lt;T&gt; 实现 IReadOnlyCollection&lt;T&gt; 而事实上 List&lt;T&gt; implements both IList&lt;T&gt; and IReadOnlyList&lt;T&gt; implies that it should
  • @Stijn 我知道这是必要的,因为存在向后兼容性问题。但请注意,您链接的答案中的“原因 #2”是只读意味着不可变的错误误解。我可能会说 MS 错了,因为他们在想到 IReadOnlyCollection&lt;T&gt; 之前就发送了 ICollection&lt;T&gt;。如果 .net 重新开始并且没有向后兼容性问题,我敢肯定他们会毫不犹豫地将 ICollection&lt;T&gt; 设为 IReadOnlyCollection&lt;T&gt;。我也不确定您是否可以说接口继承,因为成员与父级保持一致。

标签: c# icollection


【解决方案1】:

鉴于它们都继承自 IEnumerable&lt;T&gt;,您可以通过对其进行扩展来避免歧义问题:

public static class IEnumerableExtensions
{
    public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
    {
        return enumerable == null || !enumerable.Any();
    }
}

【讨论】:

  • enumerable.Count() == 0 枚举enumerable 中的所有项目。最好使用!enumerable.Any()
  • 没错,我想让它保持简单,但这是一个有效的性能优化。我会更新我的答案。
  • 如果你的扩展实现需要知道集合的Count,这不是理想的解决方案。该属性似乎是ICollection&lt;T&gt;IReadOnlyCollection&lt;T&gt; 让您超过IEnumerable&lt;T&gt; 的一件事。但是,the implementation of Enumerable.Count&lt;T&gt;() will try upcasting to ICollection&lt;T&gt; first,防止了大多数不必要的枚举。
  • 正如 binki 所说,这不是最好的方法。例如,字符串实现了 IEnumerable 接口,但既不是 ICollection 也不是 IReadOnlyCollection,并且您不希望泛型函数接受字符串类型。
猜你喜欢
  • 2014-05-21
  • 2017-03-12
  • 1970-01-01
  • 2013-06-24
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
  • 2019-04-23
相关资源
最近更新 更多