如何在 C# 中使用 string.Empty 或 String.Empty 來初始化字串?


在 C# 中使用 string.Empty 將字串設定為空 −

string myStr = string.Empty;

要檢查它是否為字串,請使用 IsNullOrEmpty() 方法 −

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

以下是一個示例 −

示例

 線上演示

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!

更新於: 2020 年 6 月 22 日

576 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.