C#中IsNullOrEmpty()和IsNullOrWhiteSpace()你用对了吗?

续:

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

正文:

看看如下代码执行情况

使用IsNullOrEmpty()方法:

string.IsNullOrEmpty("");   //true

string.IsNullOrEmpty(null);   //true

string.IsNullOrEmpty("     ");    //false

string.IsNullOrEmpty("\n");    //false

string.IsNullOrEmpty("\t");    //false

string.IsNullOrEmpty("hello");   //false

 

使用IsNullOrWhiteSpace()方法:

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" fasle true

 看了这些,大家都会使用IsNullOrEmpty()和IsNullOrWhiteSpace()方法了吧

posted @ 2023-04-13 14:45  夜店耍流氓  阅读(60)  评论(0编辑  收藏  举报