为了我的编程考试,我必须捍卫我写的代码。其中一行是:
if(app.Logourl == "" || app.Logourl == null)
他问我 null 和空字符串有没有区别。我告诉他区别在于 null
意味着它没有指向任何东西,所以它没有被实例化,但是空字符串是。
考试结束后,我走到他面前问他我说的对不对,因为我看到他脸上有一种滑稽的表情。他告诉我它们确实不同,但我检查值的顺序不正确。
几天后,我相信订单没有任何问题。我说得对吗?
长话短说
是
if(app.Logourl == "" || app.Logourl == null)
相当于
if(app.Logourl == null || app.Logourl == "")
最佳答案
你这样做没问题,因为 System.String
的 ==
重载调用了 String.Equals
,它允许 null
。
然而,这并不通用:如果您想检查字符串长度而不是使用 == ""
,您的第一个代码片段就会遇到麻烦:
if(app.Logourl.Length == 0 || app.Logourl == null) // <<== Wrong!
第二个就好了:
if(app.Logourl == null || app.Logourl.Length == 0) // <<== Correct
原因是 ||
和 &&
运算符的计算短路:一旦他们知道结果(true
for ||
, false
for &&
) 他们停止评估。在上面的第二个片段中,如果 app.Logourl
是 null
,表达式的后半部分将被忽略,因此 app.Logourl.Length
不会抛出空引用异常。
注意:认识到像这样的检查到处都是,C# 类库 offers a convenience method for doing this check :
if (string.IsNullOrEmpty(app.Logourl)) {
...
}
关于c# - 检查字符串是否为 null 或空的顺序是否重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28250649/