微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[C#]C# 中 IsNullOrEmpty 和 IsNullOrWhiteSpace 你用对了吗?

前言

C#中判断字段是否为空或者Null的时候,我们一般会使用到IsNullOrEmpty和IsNullOrWhiteSpace方法,这两个方法在大部分情况下判断的结果是一致的,但是有些情况下是不一致的。

正文

我们创建了一个 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?

是的,除非你有特定的原因将表中最后的三个值视为有效字符。

来自:
https://www.code4it.dev/csharptips/string-isnullorempty-isnullorwhitespace

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐