String.IsNullOrWhiteSpace和String.IsNullOrEmpty的区别

以前刚入行的时候判断字符串的时候用

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组合使用。

posted @ 2014-05-14 10:36  乄蛇  阅读(25286)  评论(3编辑  收藏  举报