System.String.IsNullOrEmpty 方法

本文提供了此 API 参考文档的补充说明。

IsNullOrEmpty 是一种方便的方法,可用于同时测试 is Stringnull 还是其值 String.Empty。 它等效于以下代码:

bool TestForNullOrEmpty(string s)
{
    bool result;
    result = s == null || s == string.Empty;
    return result;
}

string s1 = null;
string s2 = "";
Console.WriteLine(TestForNullOrEmpty(s1));
Console.WriteLine(TestForNullOrEmpty(s2));

// The example displays the following output:
//    True
//    True
result = s Is Nothing OrElse s = String.Empty
let testForNullOrEmpty (s: string): bool =
    s = null || s = String.Empty

let s1 = null
let s2 = ""

printfn "%b" (testForNullOrEmpty s1)
printfn "%b" (testForNullOrEmpty s2)

// The example displays the following output:
//    true
//    true

可以使用该方法 IsNullOrWhiteSpace 测试字符串 null是字符串、其值为 String.Empty还是只包含空格字符。

什么是 null 字符串?

null如果字符串尚未分配值(以 C++ 和 Visual Basic 为单位),或者它已显式分配了null一个值,则为字符串指定了一个值。 尽管复合格式设置功能可以正常处理 null 字符串,如以下示例所示,如果复合格式设置功能的成员引发 null 字符串,则尝试调用一个NullReferenceException字符串。

  String s = null;

  Console.WriteLine("The value of the string is '{0}'", s);

  try 
  {
      Console.WriteLine("String length is {0}", s.Length);
  }
  catch (NullReferenceException e) 
  {
      Console.WriteLine(e.Message);
  }

  // The example displays the following output:
  //     The value of the string is ''
  //     Object reference not set to an instance of an object.
Module Example
   Public Sub Main()
      Dim s As String

      Console.WriteLine("The value of the string is '{0}'", s)

      Try 
         Console.WriteLine("String length is {0}", s.Length)
      Catch e As NullReferenceException
         Console.WriteLine(e.Message)
      End Try   
   End Sub
End Module
' The example displays the following output:
'     The value of the string is ''
'     Object reference not set to an instance of an object.
let (s: string) = null

printfn "The value of the string is '%s'" s

try
    printfn "String length is %d" s.Length
with
    | :? NullReferenceException as ex -> printfn "%s" ex.Message

// The example displays the following output:
//     The value of the string is ''
//     Object reference not set to an instance of an object.

什么是空字符串?

如果显式分配了空字符串(“”)或 String.Empty,则字符串为空。 空字符串的值为 Length 0。 以下示例创建一个空字符串,并显示其值及其长度。

String s = "";
Console.WriteLine("The length of '{0}' is {1}.", s, s.Length);

// The example displays the following output:
//       The length of '' is 0.
Dim s As String = ""
Console.WriteLine("The length of '{0}' is {1}.", s, s.Length)
' The example displays the following output:
'        The length of '' is 0.
let s = ""
printfn "The length of '%s' is %d." s s.Length

// The example displays the following output:
//       The length of '' is 0.