检查一个数组是否为null或空。

3

我需要验证我的字符串数组是否为null或空。以下是我的代码。两种方法都不起作用。尽管该数组未初始化任何值,但它显示为包含值。有人能帮忙吗?

string abc[] = new string[3];

first code 

if(abc != null)
{

}

second code 

if(IsNullOrEmpty(abc))
{

}

public static bool IsNullOrEmpty<T>(T[] array)
{
    return array == null || array.Length == 0;
}

2
你的数组既不为空也不为空。所以你的代码正常工作。 - undefined
尽管数组没有初始化任何值,但它显示出似乎包含了值。它是在哪里显示的? - undefined
你有没有尝试过使用 bool IsNullOrEmpty(string[] array) { return array == null || array.Any(x => String.IsNullOrEmpty(x)); } 这个方法?数组元素可能是 null 或者 String.Empty(如果这是你想要检查的内容),数组本身可以是 null 或者长度为0(但是不能在你的代码中)。你可以根据需要自由地将 .Any 替换为 .All(请参考MSDN)。 - undefined
1
-6个踩,观看次数达到16k... - undefined
1个回答

23

这一行:

string abc[] = new string[3];

创建一个非空的数组(大小为3,包含3个null引用)。
因此,IsNullOrEmpty()返回false是当然的。
也许您还想检查数组是否仅包含null引用?您可以这样做:
public static bool IsNullOrEmpty<T>(T[] array) where T: class
{
    if (array == null || array.Length == 0)
        return true;
    else
        return array.All(item => item == null);
}

1
将此方法转换为扩展方法,使用 IsNullOrEmpty<T>(this T[] array) - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接