我正在使用C#11.0,看到了一些奇怪的行为,这是我以前从未见过的.但我确信这种行为并不是因为我正在使用的C#版本. 以下是对我看到的行为(代码)的解释:
char a1='a';
string s1=char.ToString(a1);
string s2 = s1.Substring(1);
代码执行后,s2
的值为string.Empty
(即""
).这很奇怪,因为s1
只有一个字符,s1.Substring(1)
应该是IndexOutOfRangeException
.这是因为,子串的定义是Substring(int startIndex)
.而s1.Substring(1)
位于s1
的界限之外(像大多数语言一样,string
从C#中的第0个索引开始).
我也在即时窗口中try 了一下,结果如下:
s1
"a"
s1[0]
97 'a'
s1[1]
's1[1]' threw an exception of type 'System.IndexOutOfRangeException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233080
HelpLink: null
InnerException: null
Message: "Index was outside the bounds of the array."
Source: "System.Private.CoreLib"
StackTrace: " at System.ThrowHelper.ThrowIndexOutOfRangeException()\r\n at System.String.get_Chars(Int32 index)"
TargetSite: {Void ThrowIndexOutOfRangeException()}
s1.Substring(0)
"a"
s1.Substring(1)
""
虽然s1.Substring(2)
正确地给出了ArgumentOutOfRangeException
.但是,我不明白为什么s1.Substring(1)
返回Empty
字符串(即""
).
任何帮助都将不胜感激.谢谢!
仅供参考-我支持的答案是明确的,对我提出的问题更有意义.即:[[Returns] A string that is equivalent to the substring that begins at startIndex in this instance, or Empty if startIndex is equal to the length of this instance.]