ICollection / ICollection 歧义问题
只想对语法sygar进行简单的扩展:
public static bool IsNotEmpty(this ICollection obj) { return ((obj != null) && (obj.Count > 0)); } public static bool IsNotEmpty(this ICollection obj) { return ((obj != null) && (obj.Count > 0)); }
当我使用一些collections品时,它可以很好地工作,但是当我与其他人合作时,我得到了
以下方法或属性之间的调用不明确:’PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.IList)’和’PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.Generic.ICollection)’
这个问题有任何规范的解决方案吗?
不,我不想在调用此方法之前执行强制转换;)
这是因为有些集合实现了两个接口,你应该将集合转换为这样的具体接口
((ICollection)myList).IsNotEmpty();
要么
((ICollection)myIntList).IsNotEmpty();
如果obj == null你会得到NullReferanceException,所以你可以删除null check;)这意味着你的扩展方法只是比较Count whith 0,你可以在没有扩展方法的情况下做;)
解决歧义的最佳方法:为所有常见的非genericsICollection类定义重载。 这意味着自定义ICollection将不兼容,但随着generics成为规范,它并没有什么大不了的。
这是整个代码:
/// /// Check the given array is empty or not /// public static bool IsNotEmpty(this Array obj) { return ((obj != null) && (obj.Length > 0)); } /// /// Check the given ArrayList is empty or not /// public static bool IsNotEmpty(this ArrayList obj) { return ((obj != null) && (obj.Count > 0)); } /// /// Check the given BitArray is empty or not /// public static bool IsNotEmpty(this BitArray obj) { return ((obj != null) && (obj.Count > 0)); } /// /// Check the given CollectionBase is empty or not /// public static bool IsNotEmpty(this CollectionBase obj) { return ((obj != null) && (obj.Count > 0)); } /// /// Check the given DictionaryBase is empty or not /// public static bool IsNotEmpty(this DictionaryBase obj) { return ((obj != null) && (obj.Count > 0)); } /// /// Check the given Hashtable is empty or not /// public static bool IsNotEmpty(this Hashtable obj) { return ((obj != null) && (obj.Count > 0)); } /// /// Check the given Queue is empty or not /// public static bool IsNotEmpty(this Queue obj) { return ((obj != null) && (obj.Count > 0)); } /// /// Check the given ReadOnlyCollectionBase is empty or not /// public static bool IsNotEmpty(this ReadOnlyCollectionBase obj) { return ((obj != null) && (obj.Count > 0)); } /// /// Check the given SortedList is empty or not /// public static bool IsNotEmpty(this SortedList obj) { return ((obj != null) && (obj.Count > 0)); } /// /// Check the given Stack is empty or not /// public static bool IsNotEmpty(this Stack obj) { return ((obj != null) && (obj.Count > 0)); } /// /// Check the given generic is empty or not /// public static bool IsNotEmpty(this ICollection obj) { return ((obj != null) && (obj.Count > 0)); }
请注意,我不希望它在IEnumerable
,因为如果您正在使用Linq-to-Entity或Linq-to-SQL,则Count()
是一种可以触发数据库请求的方法。