Mos*_*ose 5 c# extension-methods icollection ambiguous
只是想对语法 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));
}
Run Code Online (Sandbox Code Playgroud)
当我使用某些集合时,它工作得很好,但是当我与其他集合一起工作时,我得到了
以下方法或属性之间的调用不明确:“PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.IList)”和“PowerOn.ExtensionsBasic.IsNotEmpty(System.Collections.Generic.ICollection)”
这个问题有规范的解决方案吗?
不,我不想在调用此方法之前执行强制转换;)
我解决歧义的最佳方法是:为所有常见的非泛型 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));
}
Run Code Online (Sandbox Code Playgroud)
请注意,我不希望它在 上工作IEnumerable<T>,因为Count()如果您使用 Linq-to-Entity 或 Linq-to-SQL,则 是一种可以触发数据库请求的方法。