在 C# 中檢查物件是否為空
    
    Muhammad Maisam Abbas
    2024年2月16日
    
    Csharp
    Csharp Object
    
 
本教程將討論在 C# 中檢查物件是否為空的方法。
在 C# 中使用 == 運算子檢查空物件
    
C# 中的二進位制運算子 == 可以檢查運算子左邊的值是否等於運算子右邊的值。以下程式碼示例向我們展示瞭如何使用 C# 中的 == 運算子檢查物件是否為空。
using System;
namespace check_null_object {
  class Program {
    static void Main(string[] args) {
      string check = null;
      if (check == null) {
        Console.WriteLine("check is null");
      } else {
        Console.WriteLine("check is not null");
      }
    }
  }
}
輸出:
check is null
上面的程式碼使用 C# 中的 == 二進位制運算子檢查字串變數 check 是否為 null。
在 C# 中使用 is 關鍵字檢查空物件
    
我們還可以使用 is 關鍵字在 C# 中檢查物件是否為空。在 C# 中,is 關鍵字可以用作二進位制運算子 == 的替代。以下程式碼示例向我們展示瞭如何使用 C# 中的 is 關鍵字確定物件是否為空。
using System;
namespace check_null_object {
  class Program {
    static void Main(string[] args) {
      string check = null;
      if (check is null) {
        Console.WriteLine("check is null");
      } else {
        Console.WriteLine("check is not null");
      }
    }
  }
}
輸出:
check is null
上面的程式碼使用 C# 中的 == 二進位制運算子檢查字串變數 check 是否為 null。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn