String.IsNullOrWhiteSpace(String) 方法

定义

指示指定的字符串是 null、空还是仅由空白字符组成。

C#
public static bool IsNullOrWhiteSpace(string value);
C#
public static bool IsNullOrWhiteSpace(string? value);

参数

value
String

要测试的字符串。

返回

如果 true 参数为 valuenull,或者如果 Empty 仅由空白字符组成,则为 value

示例

以下示例创建一个字符串数组,然后将数组的每个元素传递给 IsNullOrWhiteSpace 方法。

C#
using System;

public class Example
{
   public static void Main()
   {
      string[] values = { null, String.Empty, "ABCDE", 
                          new String(' ', 20), "  \t   ", 
                          new String('\u2000', 10) };
      foreach (string value in values)
         Console.WriteLine(String.IsNullOrWhiteSpace(value));
   }
}
// The example displays the following output:
//       True
//       True
//       False
//       True
//       True
//       True

注解

IsNullOrWhiteSpace 是一种类似于以下代码的便捷方法,只不过它提供卓越的性能:

C#
return String.IsNullOrEmpty(value) || value.Trim().Length == 0;

空格字符由 Unicode 标准定义。 方法IsNullOrWhiteSpace将返回 值的任何字符解释为空白字符传递给Char.IsWhiteSpace方法时返回的值true

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另请参阅