2011-03-07 39 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。