我们创建了一个 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
?
是的,除非您有特定的原因将表中最新的三个值视为有效字符。