什么是"索引超出范围"例外,如何解决呢? [英] What is an "index out of range" exception, and how do I fix it?
问题描述
我收到以下错误之一:
- 在索引超出范围。必须为非负数且小于集合的大小
- 在插入索引超出范围。必须为非负数且小于或等于大小。
- 在索引数组的范围以外。
这是什么意思,如何解决呢?
What does it mean, and how do I fix it?
另请参见
<一href="http://msdn.microsoft.com/en-us/library/system.indexoutofrangeexception">IndexOutOfRangeException
<一href="http://msdn.microsoft.com/en-US/library/system.argumentoutofrangeexception">ArgumentOutOfRangeException
See Also
IndexOutOfRangeException
ArgumentOutOfRangeException
推荐答案
由于您试图访问一个元素的集合,使用超过了集合的边界数字索引。
Why does this error occur?
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
在集合的第一个元素通常位于指数 0
。最后一个元素的索引为 N-1
,其中 N
是尺寸
(它包含的元素的数量)。如果您尝试使用负数作为索引,或一个数字,是不是尺寸-1
时,你会得到一个错误。
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
当你声明数组是这样的:
When you declare an array like this:
var array = new int[6]
数组中的第一和最后一个元素是
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
所以,当你写的:
So when you write:
var element = array[5];
您检索的阵列,而不是第五个第六元素。
you are retrieving the sixth element in the array, not the fifth one.
通常情况下,你会遍历一个这样的数组:
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
这工作,因为循环从0开始,结束于长度-1
,因为首页
不再小于长度
。
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
然而,这会抛出异常:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
注意&LT; =
呢? 首页
现在将超出范围的最后一个循环迭代,因为循环认为长度
是有效的索引,但事实并非如此。
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
列表的工作方式相同,不同之处在于,通常可使用计数
而不是长度
。他们仍然从0开始,而结束于计数 - 1
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
不过,您也可以通过列表,使用迭代的foreach
,避免索引的整个问题完全是:
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
您不能索引还没有被添加到一个集合又一个元素。
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
这篇关于什么是&QUOT;索引超出范围&QUOT;例外,如何解决呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!