如何在 C# 中将字符串初始化为空字符串?
csharpprogrammingserver side programming更新于 2025/5/25 4:37:17
将字符串初始化为空列表 −
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!

