什么是“索引超出范围"?异常,我该如何解决? [英] What is an "index out of range" exception, and how do I fix it?

查看:397
本文介绍了什么是“索引超出范围"?异常,我该如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误之一:

  • 索引超出范围.必须为非负且小于集合的大小"
  • 插入索引超出范围.必须为非负且小于或等于大小."
  • 索引超出数组范围."

这是什么意思,我该如何解决?

What does it mean, and how do I fix it?

另见
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 是集合的 Size(它包含的元素数).如果您尝试使用负数作为索引,或者使用大于 Size-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];

所以当你写:

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]);
}

这是可行的,因为循环从零开始,到 Length-1 结束,因为 index 不再小于 Length.

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]);
}

注意到 <= 了吗?index 现在将在最后一次循环迭代中超出范围,因为循环认为 Length 是有效索引,但事实并非如此.

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.

列表的工作方式相同,不同之处在于您通常使用 Count 而不是 Length.它们仍然从零开始,到 Count - 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.

这篇关于什么是“索引超出范围"?异常,我该如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆