Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查数组是否为null或空_C# - Fatal编程技术网

C# 检查数组是否为null或空

C# 检查数组是否为null或空,c#,C#,我需要验证我的字符串数组是空的还是空的。两者都不起作用。虽然数组没有用任何值初始化,但它显示为包含值。有人能帮忙吗 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 ||

我需要验证我的字符串数组是空的还是空的。两者都不起作用。虽然数组没有用任何值初始化,但它显示为包含值。有人能帮忙吗

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;
}
string abc[]=新字符串[3];
第一代码
如果(abc!=null)
{
}
第二代码
if(IsNullOrEmpty(abc))
{
}
公共静态bool IsNullOrEmpty(T[]数组)
{
返回数组==null | |数组。长度==0;
}
此行:

string abc[] = new string[3];
创建一个非空数组(大小为3,包含3个空引用)

当然IsNullOrEmpty()返回false

也许您还想检查数组是否只包含空引用?你可以这样做:

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);
}
公共静态bool为空(T[]数组),其中T:class
{
if(array==null | | array.Length==0)
返回true;
其他的
返回数组.All(item=>item==null);
}

您的数组既不是null也不是空的。因此,您的代码可以正常工作。
虽然数组没有用它显示的任何值初始化,好像它包含值一样
它在哪里显示?您是否尝试使用
bool IsNullOrEmpty(string[]array){return array==null | | array.any(x=>string.IsNullOrEmpty(x))}
。数组元素可以是
null
String。空的
(如果这是您要检查的),数组本身可以是
null
或0长度(但不在代码中)。请随意将
.Any
替换为
.All
(请参阅MSDN)。-6次向下投票,16k视图…若要将其转换为扩展方法,请使用
IsNullOrEmpty(此T[]数组)