【问题标题】:Bug in C# - "FooBar".StartsWith(string.Empty) is true [duplicate]C# 中的错误 - "FooBar".StartsWith(string.Empty) 为真 [重复]
【发布时间】:2011-03-07 14:32:52
【问题描述】:

可能重复:
Why does “abcd”.StartsWith(“”) return true?

类似这样的真实情况让我们大吃一惊:

"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 为假,文化为空。那么为什么“this == value”的计算结果为 true?

【问题讨论】:

标签: c# string


【解决方案1】:

不是this == value 返回true,而是CompareInfo.IsPrefixdocumented 作为返回trueString.Empty

每个字符串都以 空子字符串(“”);因此,如果 前缀是一个空字符串,这个方法 返回真。

【讨论】:

    【解决方案2】:

    你为什么认为"this == value" evaluate to true?我相信这种行为是正确的。任何字符串都可以被认为是以空字符串开头的。

    【讨论】:

      【解决方案3】:

      实际上 FooBar 以 string.Empty 开头。任何字符串都可以考虑以string.Empty开头,以及0+a = a。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-17
        • 1970-01-01
        • 2014-09-12
        相关资源
        最近更新 更多