如何在 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+ 浏览量

职业生涯起步

完成课程后获得认证

立即开始
广告
© . All rights reserved.