简体   繁体   English

读取array [1]时出现array.Length> 0的IndexOutOfRangeException

[英]IndexOutOfRangeException with array.Length>0 while reading array[1]

I'm coding on an online IDE that doesn't expose either the program input nor the stdout output, in this particular case (input too big). 我在一个在线IDE上进行编码,在这种特殊情况下(输入太大),该IDE不公开程序输入也不输出stdout输出。

Considering file to be an arbitrary string: file视为任意字符串:

if (!string.IsNullOrEmpty(file))
{
    string[] splitted = file.Split('.');
    if (splitted.Length > 0)
    {
        string Test = splitted[1];
    }
}

How is it possible that the code above returns this error: 上面的代码如何可能返回此错误:

UNHANDLED EXCEPTION: System.IndexOutOfRangeException: ~message masked~ 
  at Solution.Solution.Main (System.String[] args) [0x000e4] in solution.cs:6

Line number is always wherever I try to access splitted[1] . 行号始终是我尝试访问splitted[1]任何地方。 This doesn't make any sense: if splitted.Length > 0 then splitted[1] exists. 这没有任何意义:如果splitted.Length > 0则存在splitted[1]

Is this a bug of the online IDE? 这是在线IDE的错误吗? Or is there any condition in which a C# string[] can be of Lenght>0 and throw IndexOutOfRangeException while reading it's value at [1]? 还是有任何条件使得C#字符串[]的长度可以大于0并在读取[1]的值时抛出IndexOutOfRangeException?

You're checking if the array is longer than 0, then trying to reference the second element within the array. 您正在检查数组是否长于0,然后尝试引用数组中的第二个元素。 If the length is 1, that's an error. 如果长度为1,则错误。

If you always need the second element, check that the array has at least two elements: 如果始终需要第二个元素,请检查该数组是否至少包含两个元素:

if (splitted.Length > 1)

Alternatively, if you're trying to access the first element: 或者,如果您尝试访问第一个元素:

string Test = splitted[0];

In c#, array indexing starts at 0 . 在c#中,数组索引从0开始。 It looks like in the line of code string Test = splitted[1]; 看起来像是代码string Test = splitted[1]; that you're trying to access the first element in splitted , but since indexing starts at 0 , the element in index 1 will be the second. 您尝试访问splitted的第一个元素,但是由于索引从0开始,因此索引1的元素将是第二个元素。

You want to change this to string Test = splitted[0]; 您想将其更改为string Test = splitted[0];

C#中的数组始终从0开始索引。您应该尝试splitted [0]

C# uses zero based index. C#使用基于零的索引。 Splitted[0] is guaranteed to exist in your conditional as that is the first element in the array. 保证条件中存在Splitted [0],因为条件条件是数组中的第一个元素。 Splitted [1] is the second element in the array. Splitted [1]是数组中的第二个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM