c# – ICollection / ICollection歧义问题

只想为syntactic sygar进行简单的扩展:

public static bool IsNotEmpty(this ICollection obj)
{
    return ((obj != null)
        && (obj.Count > 0));
}

public static bool IsNotEmpty<T>(this ICollection<T> obj)
{
    return ((obj != null)
        && (obj.Count > 0));
}

当我处理一些收藏品时,它可以很好地工作,但是当与其他人合作时,我得到了

The call is ambiguous between the
following methods or properties:
‘PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.IList)’
and
‘PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.Generic.ICollection)’

这个问题有任何规范的解决方案吗?

不,我不想在调用此方法之前执行强制转换;)

解决方法:

这是因为有些集合实现了两个接口,你应该将集合转换为这样的具体接口

((ICollection)myList).IsNotEmpty();

要么

((ICollection<int>)myIntList).IsNotEmpty();

如果obj == null你会得到NullReferanceException,所以你可以删除null check;)这意味着你的扩展方法只是比较Count whith 0,你可以在没有扩展方法的情况下做;)

上一篇:Windows Server 2016-批量设置用户下次登陆须更改密码


下一篇:关于MyBatis报错Column 'id' in where clause is ambiguous的问题