5

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

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<IReadOnlyCollection<myType>>(),我希望它只是myList.IsEmpty()

这可能吗?

4

1 回答 1

3

鉴于它们都从IEnumerable<T>您那里继承,可以通过对其进行扩展来避免歧义问题:

public static class IEnumerableExtensions
{
    public static bool IsEmpty<T>(this IEnumerable<T> enumerable)
    {
        return enumerable == null || !enumerable.Any();
    }
}
于 2013-09-05T05:32:08.623 回答