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
如上所示,这两种方法的行为办法不同。如果我们想以表格办法查当作果,可以看到如下内容:
valueIsNullOrEmptyIsNullOrWhiteSpace"Hello"falsefalse""truetruenulltruetrue" "falsetrue"\n"falsetrue"\t"falsetrue
总结
你是否必须将所有 String.IsNullOrEmpty 更换为 String.IsNullOrWhiteSpace?
是的,除非你有特定的缘故原由将表中末了的三个值视为有效字符。
转自:Davide Bellone
链接:code4it.dev/csharptips/string-isnullorempty-isnullorwhitespace