为ICollection的和IReadOnlyCollection扩展方法 [英] Extension methods for both ICollection and IReadOnlyCollection

查看:429
本文介绍了为ICollection的和IReadOnlyCollection扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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



但是,当我带班implemeting两个接口使用它,我显然得到了暧昧调用。
我不想键入 myList.IsEmpty< IReadOnlyCollection<的myType>>(),我希望它只是 myList中.IsEmpty()

这可能吗?

推荐答案

既然他们都从的IEnumerable<继承; T> 则可以通过上,而不是做一个扩展避免歧义问题b

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

这篇关于为ICollection的和IReadOnlyCollection扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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