检查数组或集合没有为null的元素

/// <summary>

/// 检查给定数组或集合是否具有元素,并且没有一个元素为null
/// </summary>
/// <param name="collection">the collection to be checked.</param>
/// <returns>true if the collection has a length and contains only non-null elements.</returns>
public static bool HasElements(ICollection collection)
{
if (!HasLength(collection)) return false;
IEnumerator it = collection.GetEnumerator();
while (it.MoveNext())
{
if (it.Current == null) return false;
}
return true;
}

/// <summary>
/// Checks if the given array or collection is null or has no elements.
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
public static bool HasLength(ICollection collection)
{
return !((collection == null) || (collection.Count == 0));
}

 备注:GetEnumerator是返回实例的枚举数。换句话说就是将集合中的所有元素一个一个列出来。我们可以通过MoveNext()得到集合中的 所有元素

posted @ 2018-09-20 09:21  蹦蹦郭  阅读(525)  评论(0编辑  收藏  举报