要将字符串初始化为空列表-
string myStr = null;
现在,使用内置方法IsNullOrEmpty()检查列表是否为空-
if (string.IsNullOrEmpty(myStr)) {
Console.WriteLine("字符串为空或空!");
}让我们看完整的代码-
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
string myStr = null;
if (string.IsNullOrEmpty(myStr)) {
Console.WriteLine("字符串为空或空!");
}
Console.ReadKey();
}
}
}输出结果
字符串为空或空!
将字符串初始化为空字符串的另一种方法,请尝试以下代码。在这里,我们使用了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("字符串为空或空!");
} else {
Console.WriteLine("String isn't empty or null!");
}
}
}
}输出结果
字符串为空或空!