只想对句法系统进行简单的扩展:
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)’
这个问题有规范的解决方案吗?
不,我不想在调用此方法之前执行强制转换;)
发布于 2009-10-12 10:43:23
解决歧义的最佳方法是:为所有常见的非泛型ICollection类定义重载。这意味着自定义ICollection将不兼容,但这不是什么大不了的,因为泛型正在成为常态。
以下是整个代码:
/// <summary>
/// Check the given array is empty or not
/// </summary>
public static bool IsNotEmpty(this Array obj)
{
return ((obj != null)
&& (obj.Length > 0));
}
/// <summary>
/// Check the given ArrayList is empty or not
/// </summary>
public static bool IsNotEmpty(this ArrayList obj)
{
return ((obj != null)
&& (obj.Count > 0));
}
/// <summary>
/// Check the given BitArray is empty or not
/// </summary>
public static bool IsNotEmpty(this BitArray obj)
{
return ((obj != null)
&& (obj.Count > 0));
}
/// <summary>
/// Check the given CollectionBase is empty or not
/// </summary>
public static bool IsNotEmpty(this CollectionBase obj)
{
return ((obj != null)
&& (obj.Count > 0));
}
/// <summary>
/// Check the given DictionaryBase is empty or not
/// </summary>
public static bool IsNotEmpty(this DictionaryBase obj)
{
return ((obj != null)
&& (obj.Count > 0));
}
/// <summary>
/// Check the given Hashtable is empty or not
/// </summary>
public static bool IsNotEmpty(this Hashtable obj)
{
return ((obj != null)
&& (obj.Count > 0));
}
/// <summary>
/// Check the given Queue is empty or not
/// </summary>
public static bool IsNotEmpty(this Queue obj)
{
return ((obj != null)
&& (obj.Count > 0));
}
/// <summary>
/// Check the given ReadOnlyCollectionBase is empty or not
/// </summary>
public static bool IsNotEmpty(this ReadOnlyCollectionBase obj)
{
return ((obj != null)
&& (obj.Count > 0));
}
/// <summary>
/// Check the given SortedList is empty or not
/// </summary>
public static bool IsNotEmpty(this SortedList obj)
{
return ((obj != null)
&& (obj.Count > 0));
}
/// <summary>
/// Check the given Stack is empty or not
/// </summary>
public static bool IsNotEmpty(this Stack obj)
{
return ((obj != null)
&& (obj.Count > 0));
}
/// <summary>
/// Check the given generic is empty or not
/// </summary>
public static bool IsNotEmpty<T>(this ICollection<T> obj)
{
return ((obj != null)
&& (obj.Count > 0));
}请注意,我不希望它在IEnumerable<T>上工作,因为Count()是一种可以触发数据库请求的方法,如果您正在使用Linq或Linq。
发布于 2009-10-09 15:35:10
因为有些集合实现了这两个接口,所以应该将集合转换为如下所示的具体接口
((ICollection)myList).IsNotEmpty();或
((ICollection<int>)myIntList).IsNotEmpty();是的,如果obj ==为null,您将得到==,因此您可以删除null检查;)这意味着您的扩展方法只是将计数与0进行比较,而不使用扩展方法;)
https://stackoverflow.com/questions/1544480
复制相似问题