C# 初始化的字符串似乎包含字符串。空

C# 初始化的字符串似乎包含字符串。空,c#,contains,string-comparison,string,C#,Contains,String Comparison,String,我无意中跳进了这个,不知道为什么会发生这种事 string sample = "Hello World"; if (sample.Contains(string.Empty)) { Console.WriteLine("This contains an empty part ? at position " + sample.IndexOf(string.Empty)); Console.WriteLine(sample.LastIndexOf(string.Empty));

我无意中跳进了这个,不知道为什么会发生这种事

string sample = "Hello World";
if (sample.Contains(string.Empty))
{
    Console.WriteLine("This contains an empty part ? at position " + sample.IndexOf(string.Empty));
    Console.WriteLine(sample.LastIndexOf(string.Empty));
    Console.WriteLine(sample.Length);
}
输出

这是否包含一个空零件?在位置0处

10

11

我对最后一部分很满意,但我不知道为什么这是正确的。甚至
Indexof
LastIndexOf
都有单独的值

谁能帮我解释一下为什么会这样

编辑

我相信这与我的问题有点相关,也会对那些偶然发现这个问题的人有所帮助


请参阅此SO链接:

问题:字符串
“Hello World”
是否包含string.Empty

回答:是

每个可能的字符串都包含string.Empty,因此测试正确返回true

如果您试图测试字符串是否为空,那么下面的代码就是您想要的

if (string.IsNullOrEmpty(sample)) 
{

}
从msdn获取

如果值为String.Empty,则返回值为0

为了

如果值为String.Empty,则返回值是此实例中的最后一个索引位置

为了

如果value参数出现在此字符串中,或者value为空字符串(“”),则为true

这记录在以下文件中:

返回值
类型:System.Boolean
true
如果value参数出现在此字符串中,或者value是空字符串(“”);否则,
false

而且

如果值为String.Empty,则返回值为0

而且

如果值为String.Empty,则返回值是此实例中的最后一个索引位置


@SwDevMan81:那不是应该是11而不是10吗?@V4Vendetta-最后一个索引是10(0到10是11个字符)@SwDevMan81:对不起,我的错误没有读到
索引
,所以这是否意味着对于上面给出的任何字符串。Empty将始终解析为true(很高兴知道是否有例外情况)@V4Vendetta-是的,如果输入为字符串,则它将始终返回true。Empty@SwDevMan81当前位置我在看更多关于
为什么它会这样做