IsNullOrEmpty等效于Array?C#

max*_*axp 40 c# arrays

.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方法.

  • 如果对可能为空的引用调用扩展方法确实让您烦恼,您还可以使用语法 `ExtensionClass.IsNullOrEmpty(arr)` (这是编译器有效执行的操作),但这不是使用扩展方法的正常方法扩展方法。 (2认同)

Lee*_*Lee 28

您可以创建自己的扩展方法:

public static bool IsNullOrEmpty<T>(this T[] array)
{
    return array == null || array.Length == 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 我其实比这更好地喜欢这个答案:) (4认同)

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)


Dan*_*kin 8

如果你使用更通用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)