IsNullOrWhiteSpace和IsNullOrEmpty这两个方法是与判断string字符串是否为空有关的两个方法。二者用来对比学习。
IsNullOrWhiteSpace方法是用来判断指示指定的字符串是 null、空还是仅由空白字符组成。输入参数是一个字符串,输出是bool类型,如果字符串是null或空或由空白字符串组成,返回True,否则返回False。
IsNullOrEmpty方法用来判断指示指定的字符串是 null 还是空字符串 (“”)。输入输出与IsNullOrWhiteSpace方法类型一致。
下面使用简单的语句对这两个方法进行测试说明:
string str1 = "";
string str2 = null;
string str3 = string.Empty;
string str6 = "\t";
string str7 = new string(' ', 10);
string str8 = new string('a', 10);
bool a = string.IsNullOrWhiteSpace(str1);
bool a1 = string.IsNullOrEmpty(str1);
bool b = string.IsNullOrWhiteSpace(str2);
bool b1 = string.IsNullOrEmpty(str2);
bool c = string.IsNullOrWhiteSpace(str3);
bool c1 = string.IsNullOrEmpty(str3);
bool f = string.IsNullOrWhiteSpace(str6);
bool f1 = string.IsNullOrEmpty(str6);
bool str7_space = string.IsNullOrWhiteSpace(str7);
bool str7_enpty = string.IsNullOrEmpty(str7);
bool str8_space = string.IsNullOrWhiteSpace(str8);
bool str8_empty = string.IsNullOrEmpty(str8);
Console.WriteLine("str1为:" + str1 + "移除空白字符后长度为:" + str1.Trim().Length + "实际长度为:" + str1.Length);
Console.WriteLine("IsNullOrWhiteSpace值为:" + a + "---IsNullOrEmpty值为:" + a1);
Console.WriteLine();
Console.WriteLine("str2为:" + str2);
Console.WriteLine("IsNullOrWhiteSpace值为:" + b + "---IsNullOrEmpty值为:" + b1);
Console.WriteLine();
Console.WriteLine("str3为:" + str3 + "移除空白字符后长度为:" + str3.Trim().Length + "实际长度为:" + str3.Length);
Console.WriteLine("IsNullOrWhiteSpace值为:" + c + "---IsNullOrEmpty值为:" + c1);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("str6为:" +str6 + "移除空白字符后长度为:" + str6.Trim().Length + "实际长度为:" + str6.Length);
Console.WriteLine("IsNullOrWhiteSpace值为:" + f + "---IsNullOrEmpty值为:" + f1);
Console.WriteLine();
Console.WriteLine("str7为:" + str7 + "移除空白字符后长度为:" + str7.Trim().Length + "实际长度为:" + str7.Length);
Console.WriteLine("IsNullOrWhiteSpace值为:" + str7_space + "---IsNullOrEmpty值为:" + str7_empty);
Console.WriteLine();
Console.WriteLine("str8为:" + str8 + "移除空白字符后长度为:" + str8.Trim().Length + "实际长度为:" + str8.Length);
Console.WriteLine("IsNullOrWhiteSpace值为:" + str8_space + "---IsNullOrEmpty值为:" + str8_empty);
Console.ReadKey();
运行结果如下所示:
由运行结果可看出,当移除空白字符后长度为0时,IsNullOrWhiteSpace方法的结果为True,str7与str8对比最为明显,str7为10个空格字符,str8为10个字符a。可看出IsNullOrWhiteSpace方法可看作时 String.IsNullOrEmpty(value) || value.Trim().Length == 0;