ICollection / ICollection歧义问题
只是想为 syntropic 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));
}
当我使用某些集合时,它工作得很好,但是当与他人合作时我得到
调用之间不明确 以下方法或属性: 'PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.IList)' 和 'PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.Generic.ICollection)'
这个问题有任何规范解决方案吗?
不,我不想在调用此方法之前执行强制转换;)
Just want to make simple extension for 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));
}
It works perfectly when I work with some collections, but when working with others I get
The call is ambiguous between the
following methods or properties:
'PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.IList)'
and
'PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.Generic.ICollection)'
Is there any canonical solution to this problem ?
No, I don't want to perform a cast before calling this method ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为有些集合实现了这两个接口,您应该将集合转换为具体接口,如下所示
或者
是的,如果 obj == null,您将得到 NullReferanceException,这样您就可以删除 null 检查;) 这意味着您的扩展方法只是将 Count 与 0 进行比较你可以不用扩展方法;)
It's because some collections implements both interfaces, You should convert collection to concrete interface like this
Or
And yea, you will get NullReferanceException if obj == null so you can remove null check ;) which mean that your extension method just compares Count whith 0 which you can do without extension method ;)
我解决歧义的最佳方法是:为所有常见的非泛型 ICollection 类定义一个重载。
这意味着自定义 ICollection 将不兼容,但这没什么大不了的,因为泛型正在成为常态。
以下是完整代码:
请注意,我不希望它在
IEnumerable
上工作,因为Count()
是一种可以触发数据库请求的方法,如果您正在使用 Linq-to-Entity 或 Linq-to-SQL。My best way to solve the ambiguity : define an overload for all common non-generic ICollection classes.
That means custom ICollection won't be compatible, but it's no big deal as generics are becoming the norme.
Here is the whole code :
Note that I did not want it to work on
IEnumerable<T>
, becauseCount()
is a method that can trigger a database request if you are working with Linq-to-Entity or Linq-to-SQL.