2011-03-07 24 views
2

可能重複:
Why does 「abcd」.StartsWith(「」) return true?錯誤在C#中 - 「FooBar的」 .StartsWith(的String.Empty)爲真

類似的東西這事是否真實抓到我們了:

"FooBar".StartsWith(string.Empty) 

首先我不認爲它應該是真的,但我也不太確定它爲什麼是真的,看着「Reflector'ed」代碼:

public bool StartsWith(string value, bool ignoreCase, CultureInfo culture) 
{ 
    if (value == null) 
    { 
     throw new ArgumentNullException("value"); 
    } 
    if (this == value) 
    { 
     return true; 
    } 
    CultureInfo info = (culture == null) ? CultureInfo.CurrentCulture : culture; 
    return info.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); 
} 

ignoreCase爲false且文化爲空。那麼爲什麼「這個==值」評估爲真?

+0

退房http://stackoverflow.com/questions/145509/why-does-abcd-startswith-return-true/145516#145516 – 2011-03-07 14:36:20

+0

是的,我剛剛發現的問題,謝謝。 – NetRunner 2011-03-07 14:37:03

回答

4

這並不是說this == value回報true,但CompareInfo.IsPrefixdocumented爲返回trueString.Empty

每個字符串的開始和與 空字符串( 「」)結束;因此,如果 前綴是空字符串,則此方法 返回true。

0

爲什麼你認爲"this == value" evaluate to true?我相信這種行爲是正確的。任何字符串都可以被認爲是以空字符串開始的。

0

其實FooBar以string.Empty開頭。任何字符串都可以考慮以string.Empty開頭,以及0 + a = a。