初始化的字符串似乎包含string.Empty

V4V*_*tta 9 c# string contains string-comparison

我不小心跳进了这个,并且不知道为什么会这样

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);
}
Run Code Online (Sandbox Code Playgroud)

产量

This contains an empty part ? at position 0

10

11

我很满意最后一部分,但我不知道为什么这被评估为真.甚至Indexof并且LastIndexOf具有单独的值.

任何人都可以帮我解决这个问题的原因吗?

编辑

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

看到这个SO链接:为什么"abcd".StartsWith("")返回true?

SwD*_*n81 16

来自msdn的IndexOf

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

对于LastIndexOf

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

对于包含

如果value参数出现在此字符串中,或​​者value为空字符串(""),则返回true;否则返回false.