System.String.IsNullOrEmpty 方法

本文提供此 API 參考文件的補充備註。

IsNullOrEmpty 是一種方便的方法,可讓您同時測試 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 字串,如下列範例所示,如果其成員擲回 ,則嘗試呼叫一個 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.