• String.IsNullOrEmpty和String.IsNullOrWhiteSpace有什么区别?
  • 发布于 2个月前
  • 421 热度
    0 评论
  • BruceLe
  • 1 粉丝 54 篇博客
  •   
前言
C#中判断字段是否为空或者Null的时候,我们一般会使用到IsNullOrEmptyIsNullOrWhiteSpace方法,这两个方法在大部分情况下判断的结果是一致的,但是有些情况下是不一致的。

正文
我们创建了一个 CreateUser方法,在系统中将创建一个新用户,如下所示:
void CreateUser(string username)  
{  
    if (string.IsNullOrEmpty(username))  
        throw new ArgumentException("Username cannot be empty");  
  
    CreateUserOnDb(username);  
}  
  
void CreateUserOnDb(string username)  
{  
    Console.WriteLine("Created");  
}  
看起来很安全,对吧?第一次检查是否足够?

让我们试试:CreateUser("Loki") 打印了 Created 当使用CreateUser(null) 和 CreateUser("") 抛出了异常.使用 CreateUser(" ") 呢?不幸的是,它打印了 Created:发生这种情况是因为字符串实际上不是空的,而是由不可见的字符组成的。

转义字符也是如此!为避免这种情况,你可以 String.IsNullOrWhiteSpace  更换 String.IsNullOrEmpty 此方法也对不可见字符执行检查.所以我们测试如上内容
String.IsNullOrEmpty(""); //True  
String.IsNullOrEmpty(null); //True  
String.IsNullOrEmpty("   "); //False  
String.IsNullOrEmpty("\\n"); //False  
String.IsNullOrEmpty("\\t"); //False  
String.IsNullOrEmpty("hello"); //False 
也测试此方法
String.IsNullOrWhiteSpace("");//True  
String.IsNullOrWhiteSpace(null);//True 
String.IsNullOrWhiteSpace("   ");//True 
String.IsNullOrWhiteSpace("\\n");//True 
String.IsNullOrWhiteSpace("\\t");//True 
String.IsNullOrWhiteSpace("hello");//False  
如上所示,这两种方法的行为方式不同。如果我们想以表格方式查看结果,可以看到如下内容:
value IsNullOrEmpty IsNullOrWhiteSpace
"Hello" false false
"" true true
null true true
" " false true
"\n" false true
"\t" false true

总结
你是否必须将所有 String.IsNullOrEmpty 替换为 String.IsNullOrWhiteSpace?
是的,除非你有特定的原因将表中最后的三个值视为有效字符。
用户评论