指数数组的边界之外? [英] Index was outside the bounds of the array?
本文介绍了指数数组的边界之外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
static void Main(string[] args)
{
string[] arr = new string[4];
arr[0] = "Hemanth";
arr[1] = "Anil";
arr[2] = "Raja";
arr[3] = "Somu";
for (int i = 0; i <= arr.Length; i++)
{
string element = arr[i];
Console.WriteLine(element);
}
Console.ReadLine();
}
这是我要执行的代码,当我执行时上面的程序正在执行但是string element = arr [i];在这一行我得到索引超出数组的界限为什么?这是什么意思?
提前感谢
this is the code that i want to execute and and when i execute the above program it's getting executed but string element = arr[i]; in this line iam getting the index was outside the bounds of array why? what does it mean?
thanks in advance
推荐答案
这意味着您正在尝试从超出数组边界的索引处获取数组中的元素。在这种情况下,最大索引是3
(C#的数组索引是从零开始的,也就是说,第一个元素的索引为0),但因为你的条件是i< = arr.Length
,i
在循环的最后一次迭代时将为4,因为数组长度为4.将条件更改为i< arr.Length
然后你的循环就可以了。
It means that you are trying to get an element from the array at an index that exceeds the array's bounds. In this case, the maximum index is3
(the array indices of C# are zero-based, that is, the first element has index 0), but because your condition isi <= arr.Length
,i
will be 4 at the last iteration of the loop, because the array length is 4. Change the condition toi < arr.Length
and then your loop will work fine.
这篇关于指数数组的边界之外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文