我正在使用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.]

推荐答案

这一行为实际上在SubString's documentation中有明确的记录(为了强调,增加了我的韩元粗体):

[返回]等同于在此实例中以startIndexEmpty if 100 is equal to the length of this instance开头的子字符串的字符串.

Csharp相关问答推荐

FromServices不使用WebAppliationFactory程序>

我无法在Ubuntu下编译使用microsoft.extension.configurationbuilder jsonapi和mono mcs的c#应用程序

有没有一种方法可以在包含混合文本的标签中嵌入超链接?

==和Tuple对象的相等<>

如何注销Microsoft帐户?

此反射有什么问题.是否发送值转换委托?

Blazor Foreach仅渲染最后一种 colored颜色

(乌龙)1&#比c#中的UL&#慢吗?

WeakReference未被垃圾收集

Thad.Sept()vs Task.Delay().Wait()

如何在C#中使用Postman中的本地IP向本地主机上运行的本地API发出请求

使用预定义对象减少Task.Run/Factory.StartNew中的关闭开销

具有可空类型的C#NOTNULL约束具有意外行为

正在try 从Blazor中的API读取JSON

如何在我的C#应用程序中设置带有reactjs前端的SignalR服务器?

如何从非异步任务中正确返回TypeResult

如何使用ODP.NET C#设置Oracle会话时间长度限制

Visual Studio,Docker容器-容器调用:连接被拒绝

在Visual Studio 2022中查找Xamarin模板时遇到问题

需要帮助才能在图片框中显示C#(WinForm)中纯资源DLL中的图像