我今天在使用 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;
}
}
}
输出:
"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.
"123".Substring(3) 返回空字符串,"123".Substring(4) 抛出异常。但是,“123”[3] 和“123”[4] 都超出了范围。这是 documented on MSDN ,但我很难理解为什么 Substring 方法是这样写的。我希望任何越界索引要么总是导致异常,要么总是导致空字符串。有什么见解吗?
最佳答案
String.Substring(startindex)
的内部实现是这样的
public string Substring(int startIndex)
{
return this.Substring(startIndex, this.Length - startIndex);
}
所以你要求的是一个零字符长度的字符串。 (又名 String.Empty) 我同意你的看法,这在 MS 部分并不清楚,但如果没有更好的解释,我认为给出这个结果比抛出异常更好。
深入String.Substring(startIndex, length)
的实现我们看到这段代码
if (length == 0)
{
return Empty;
}
因此,因为 length=0 是第二个重载中的有效输入,所以我们也为第一个重载获得该结果。
关于c# - 令人惊讶的子串行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11704974/