我在使用Substring方法时遇到了这种行为:
static void Main(string[] args) {
string test = "123";
for (int i = 0; true; i++) {
try {
Console.WriteLine("\"{0}\".Substring({1}) is \"{2}\"", test, i, test.Substring(i));
} catch (ArgumentOutOfRangeException e) {
Console.WriteLine("\"{0}\".Substring({1}) threw an exception.", test, i);
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
"123".Substring(0) is "123"
"123".Substring(1) is "23"
"123".Substring(2) is "3"
"123".Substring(3) is ""
"123".Substring(4) threw an exception.
Run Code Online (Sandbox Code Playgroud)
"123".Substring(3)返回一个空字符串,"123".Substring(4)抛出异常.然而,"123"[3]和"123"[4]都是出界的.这在MSDN上有记录,但我很难理解为什么以这种方式编写Substring方法.我希望任何越界索引要么总是导致异常,要么总是导致空字符串.任何见解?
Ste*_*eve 14
内部实现String.Substring(startindex)是这样的
public string Substring(int startIndex)
{
return this.Substring(startIndex, this.Length - startIndex);
}
Run Code Online (Sandbox Code Playgroud)
所以你要求一个零字符长度的字符串.(AKA String.Empty)我同意你的观点,这在MS部分尚不清楚,但如果没有更好的解释,我认为给出这个结果比抛出异常更好.
深入了解String.Substring(startIndex, length)我们看到这段代码的实现
if (length == 0)
{
return Empty;
}
Run Code Online (Sandbox Code Playgroud)
因此,因为length = 0是第二个重载中的有效输入,所以我们也得到第一个重载的结果.