之前剛入行的時候判斷字符串的時候用spa
string a="a"; a==""; a==null;
後來發現了String.IsNullOrEmpty感受方便了好多,可是後來發現若是字符串的空白String a=" ";IsNullOrEmpty就無法判斷了,因而我今天發現了String.IsNullOrWhiteSpace,此方法只在framework4.0以上才能使用,官方的解釋是:指示指定的字符串是 null、空仍是僅由空白字符組成。code
http://msdn.microsoft.com/zh-cn/library/system.string.isnullorwhitespace(v=vs.100).aspxblog
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組合使用。input