以前剛入行的時候判斷字符串的時候用
string a="a"; a==""; a==null;
后來發現了String.IsNullOrEmpty感覺方便了好多,但是后來發現如果字符串的空白String a=" ";IsNullOrEmpty就沒法判斷了,於是我今天發現了String.IsNullOrWhiteSpace,此方法只在framework4.0以上才能使用,官方的解釋是:指示指定的字符串是 null、空還是僅由空白字符組成。
http://msdn.microsoft.com/zh-cn/library/system.string.isnullorwhitespace(v=vs.100).aspx
1 string a = null; 2 string b = string.Empty; 3 string c = ""; 4 string d = " "; 5 Console.WriteLine("a:{0};\r\n b:{1};\r\n c:{2};\r\n d:{3};\r\n", a, b, c, d); 6 if (string.IsNullOrEmpty(a)) 7 Console.WriteLine("a"); 8 if (string.IsNullOrEmpty(b)) 9 Console.WriteLine("b"); 10 if (string.IsNullOrEmpty(c)) 11 Console.WriteLine("c"); 12 if (string.IsNullOrEmpty(d)) 13 Console.WriteLine("d"); 14 15 if (string.IsNullOrWhiteSpace(a)) 16 Console.WriteLine("a1"); 17 if (string.IsNullOrWhiteSpace(b)) 18 Console.WriteLine("b1"); 19 if (string.IsNullOrWhiteSpace(c)) 20 Console.WriteLine("c1"); 21 if (string.IsNullOrWhiteSpace(d)) 22 Console.WriteLine("d1"); 23 Console.Read();
執行結果:
由此可見當用IsNullOrEmpty時,d是沒有輸出來的,但是string.IsNullOrWhiteSpace卻可以,如果執意要用前者又要判斷空白的話,不妨與Trim組合使用。