C# 字符串 - IsNullOrEmpty() 方法

C# 字符串 IsNullOrEmpty() 方法用于检查指定字符串是否为 null 或空字符串 (" ")。

如果字符串未赋值,则视为 null;如果字符串仅被赋值一对空的双引号 ("") 或 String.Empty(),则视为空字符串。

语法

以下是 C# 字符串 IsNullOrEmpty() 方法的语法 -

public static bool IsNullOrEmpty (string? value);

参数

此方法接受一个字符串值作为参数,表示要检查的字符串。

返回值

如果值参数为 null 或空字符串 (""),则此方法返回 true;否则返回 false。

示例 1:检查字符串是否为空

以下是使用 IsNullOrEmpty() 方法检查字符串是否为空的基本示例 -

  
using System;
class Program {
   static void Main() {
      string str = "";
      bool res = string.IsNullOrEmpty(str);
      if (res == true) {
         Console.WriteLine("String is empty.");
      }
      else {
         Console.WriteLine("String is neither empty nor null.");
      }
   }
}

输出

以下是输出 -

String is empty.

示例 2:检查字符串是否为空

我们来看另一个示例。这里,我们使用 IsNullOrEmpty() 方法来检查字符串是否为空 -

using System;
class Program {
   static void Main() {
      string str = null;
      bool res = string.IsNullOrEmpty(str);
      if (res == true) {
         Console.WriteLine("String is null");
      }
      else {
         Console.WriteLine("String is not null.");
      }
   }
}

输出

以下是输出 -

String is null

示例 3:区分 Null 和 Empty

在以下示例中,我们在不使用 IsNullOrEmpty 方法的情况下区分 Null 和空字符串 -

using System;
class Program {
   static void Main() {
      string str = null;
      if (str == null) {
         Console.WriteLine("String is null.");
      }
      else if (str == string.Empty) {
         Console.WriteLine("String is empty.");
      }
      else {
         Console.WriteLine("String is not null or empty.");
      }
   }
}

输出

以下是输出 -

String is null.

示例 4:如果字符串既不为 Null 也不为空会怎样?

以下示例使用 IsNullOrEmpty() 方法检查字符串是否为空。如果字符串既不为 Null 也不为空,则显示 false −

using System;
class Program {
   static void Main() {
      string str = "Hello TP";
      bool res = string.IsNullOrEmpty(str);
      if(res == true){
         Console.WriteLine("String is either Empty or Null");
      }
      else{
         Console.WriteLine("String is neither Empty nor Null");
         Console.WriteLine("string value: {0}", str);
      }
   }
}

输出

以下是输出 -

String is neither Empty nor Null
string value: Hello TP

csharp_strings.html