Extension methods for both ICollection and IReadOnlyCollection

ⅰ亾dé卋堺 提交于 2019-12-12 12:29:49

问题


I want to write an extension method (e.g. .IsEmpty()) for both ICollection and IReadonlyCollection interfaces:

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

But when I use it with classes implemeting both interfaces, I obviously get the ‘ambiguous invocation’. I don't want to type myList.IsEmpty<IReadOnlyCollection<myType>>(), I want it to be just myList.IsEmpty().

Is this possible?


回答1:


Given that they both inherit from IEnumerable<T> you could avoid the ambiguity issue by doing an extension on that instead:

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


来源:https://stackoverflow.com/questions/18627958/extension-methods-for-both-icollection-and-ireadonlycollection

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