.NET库中是否有一个函数返回true或false,表示数组是null还是空?(类似于string.IsNullOrEmpty).
我在string.IsNullOrEmpty课堂上看了一下像这样的功能但看不到任何东西.
即
var a = new string[]{};
string[] b = null;
var c = new string[]{"hello"};
IsNullOrEmpty(a); //returns true
IsNullOrEmpty(b); //returns true
IsNullOrEmpty(c); //returns false
Run Code Online (Sandbox Code Playgroud)
Pol*_*ial 52
没有现有的,但您可以使用此扩展方法:
/// <summary>Indicates whether the specified array is null or has a length of zero.</summary>
/// <param name="array">The array to test.</param>
/// <returns>true if the array parameter is null or has a length of zero; otherwise, false.</returns>
public static bool IsNullOrEmpty(this Array array)
{
return (array == null || array.Length == 0);
}
Run Code Online (Sandbox Code Playgroud)
只需将它放在某个扩展类中,它就会扩展Array为有一个IsNullOrEmpty方法.
Lee*_*Lee 28
您可以创建自己的扩展方法:
public static bool IsNullOrEmpty<T>(this T[] array)
{
return array == null || array.Length == 0;
}
Run Code Online (Sandbox Code Playgroud)
Sla*_*lai 22
随着空,条件运算在VS 2015年推出,对面是不是 NullOrEmpty可以是:
if (array?.Length > 0) { // similar to if (array != null && array.Length > 0) {
Run Code Online (Sandbox Code Playgroud)
但IsNullOrEmpty由于运算符优先级,版本看起来有点难看:
if (!(array?.Length > 0)) {
Run Code Online (Sandbox Code Playgroud)
如果你使用更通用ICollection<T>:
public static bool IsNullOrEmpty<T> (this ICollection<T> collection)
{
return collection == null || collection.Count == 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
这是(当前)投票答案的更新 C# 8 版本
public static bool IsNullOrEmpty<T>([NotNullWhen(false)] this T[]? array) =>
array == null || array.Length == 0;
Run Code Online (Sandbox Code Playgroud)