我的代码给了我某些输入超出索引范围的异常。下面是有问题的代码:
string[] snippetElements = magic_string.Split('^');
string a = snippetElements[10] == null ? "" : "hello";
string b = snippetElements[11] == null ? "" : "world";
Run Code Online (Sandbox Code Playgroud)
对于该特定输入,数组snippetElements中仅包含一个元素,因此在尝试索引第10个和第11个元素时,出现了异常。
现在,我介绍了以下检查:
if (snippetElements.Length >= 11)
{
string a = snippetElements[10] == null ? "" : "hello";
string b = snippetElements[11] == null ? "" : "world";
}
Run Code Online (Sandbox Code Playgroud)
有人可以建议一种更好的方式来写这张支票。以某种方式,数字11在代码中看起来不太好。
小智 6
是的,这是旧文章,但仍然有帮助。您可以使用我认为更干净的它:
string a = snippetElements.ElementAtOrDefault(10) ?? "hello";
string b = snippetElements.ElementAtOrDefault(11) ?? "world";
Run Code Online (Sandbox Code Playgroud)
有人可以建议一种更好的方法来写这张支票吗?不知何故,数字 11 在代码中看起来不太好。
好吧,您正在使用索引访问元素11,如果您的变量中有该索引,那么您可以在检查中使用它,否则11在检查中就可以了。您的支票应该是if(index < snippetElements.Length)
就像是:
int index = 11;
if(index < snippetElements.Length)
{
string b = snippetElements[index] == null ? "" : "world";
}
Run Code Online (Sandbox Code Playgroud)