如何在 C# 中將字串初始化為空字串?


要將字串初始化為空列表 -

string myStr = null;

現在,使用內建方法 IsNullOrEmpty() 來檢查列表是否為空 -

if (string.IsNullOrEmpty(myStr)) {
   Console.WriteLine("String is empty or null!");
}

讓我們看看完整的程式碼 -

示例

 線上演示

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         string myStr = null;

         if (string.IsNullOrEmpty(myStr)) {
            Console.WriteLine("String is empty or null!");
         }
         Console.ReadKey();
      }
   }
}

輸出

String is empty or null!

另一種將字串初始化為空字串的方法,嘗試以下程式碼。我們在此處使用了 string.Empty -

示例

 線上演示

using System;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         string myStr = string.Empty;

         if (string.IsNullOrEmpty(myStr)) {
            Console.WriteLine("String is empty or null!");
         } else {
            Console.WriteLine("String isn't empty or null!");
         }
      }
   }
}

輸出

String is empty or null!

更新於:22-6-2020

3K+ 瀏覽量

職業生涯起步

完成課程後獲得認證

立即開始
廣告