求求你不要在用!=null判空了

因为原来一直都没注意到这两个方法,一直使用string.IsNullOrEmpty,当看到string.IsNullOrWhiteSpace时,并且在微软人员开发的项目中常用时才注意到,查了一下MSDN,记一下省得之后忘记。性能

string.IsNullOrEmptyspa

都知道,这个功能是判断字符串是否为:null或者string.Empty。若是是如"\t"这样的字符就返回false了,为了达到判断过滤这些功能,就要使用Trim()和Length属性帮忙,判断是否长度为零,因而乎就产生了以下的方法。code

string.IsNullOrWhiteSpaceblog

这个是判断全部空白字符,功能至关于string.IsNullOrEmpty和str.Trim().Length总和,他将字符串给Char.IsWhiteSpace为ture的任何字符都将是正确的。根据MSDN的说明,这个方法会比调用上述两个方法的性能更高并且简洁,因此在判断这个功能时,推荐使用。开发

using System;
public class Example
{
public static void Main()
{
string[] values = { null, String.Empty, "ABCDE",
new String(' ', 20), " \t ",
new String('\u2000', 10) };
foreach (string value in values)
Console.WriteLine(String.IsNullOrWhiteSpace(value));
}
}
// The example displays the following output:
// True
// True
// False
// True
// True
// True

 

以上就是代码执行效果,至于性能就听微软的吧,不过string.IsNullOrEmpty和string.IsNullOrWhiteSpace相比,确定是前面一个性能更高,因此仍是要选择性使用的。字符串

相关文章
相关标签/搜索