問題描述
我想知道是否有特殊的方法/技巧來檢查 String
對象是否為空.我知道 String.IsNullOrEmpty
方法,但我想將 null
字符串與空字符串 (=""
) 區(qū)分開來.
I am wondering if there is a special method/trick to check if a String
object is null. I know about the String.IsNullOrEmpty
method but I want to differentiate a null
String from an empty String (=""
).
我是否應(yīng)該簡單地使用:
Should I simply use:
if (s == null) {
// blah blah...
}
...或者有其他方法嗎?
...or is there another way?
推薦答案
object 不能為 null - 表達(dá)式 的值可以為 null.值得在您的腦海中清楚地說明差異.s
的值不是一個對象 - 它是一個 reference,它要么是 null,要么指向一個對象.
An object can't be null - the value of an expression can be null. It's worth making the difference clear in your mind. The value of s
isn't an object - it's a reference, which is either null or refers to an object.
是的,你應(yīng)該使用
if (s == null)
請注意,這仍將使用字符串中定義的重載 == 運(yùn)算符,但這樣做是正確的.
Note that this will still use the overloaded == operator defined in string, but that will do the right thing.
這篇關(guān)于如何檢查字符串是否為空的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!