【问题标题】:What is an "index out of range" exception, and how do I fix it? [duplicate]什么是“索引超出范围”异常,我该如何解决? [复制]
【发布时间】:2014-09-08 20:44:31
【问题描述】:

我遇到以下错误之一:

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

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

另请参阅
IndexOutOfRangeException
ArgumentOutOfRangeException

【问题讨论】:

    标签: c# .net indexoutofrangeexception


    【解决方案1】:

    为什么会出现这个错误?

    因为您尝试使用超出集合边界的数字索引访问集合中的元素。

    集合中的第一个元素通常位于索引0。最后一个元素位于索引n-1,其中n 是集合的Size(它包含的元素数量)。如果您尝试使用负数作为索引,或者使用大于Size-1 的数字,则会出现错误。

    索引数组的工作原理

    当你像这样声明一个数组时:

    var array = new int[6]
    

    数组的第一个和最后一个元素是

    var firstElement = array[0];
    var lastElement = array[5];
    

    所以当你写的时候:

    var element = array[5];
    

    您正在检索数组中的第六个元素,而不是第五个。

    通常,您会像这样遍历数组:

    for (int index = 0; index < array.Length; index++)
    {
        Console.WriteLine(array[index]);
    }
    

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

    但是,这会引发异常:

    for (int index = 0; index <= array.Length; index++)
    {
        Console.WriteLine(array[index]);
    }
    

    注意到那里的&lt;=了吗? index 现在将在最后一次循环迭代中超出范围,因为循环认为 Length 是有效索引,但它不是。

    其他集合的工作原理

    列表的工作方式相同,只是您通常使用Count 而不是Length。它们仍然从零开始,到 Count - 1 结束。

    for (int index = 0; i < list.Count; index++)
    {
        Console.WriteLine(list[index]);
    } 
    

    但是,您也可以使用 foreach 遍历列表,从而完全避免索引的整个问题:

    foreach (var element in list)
    {
        Console.WriteLine(element.ToString());
    }
    

    您不能索引尚未添加到集合中的元素。

    var list = new List<string>();
    list.Add("Zero");
    list.Add("One");
    list.Add("Two");
    Console.WriteLine(list[3]);  // Throws exception.
    

    【讨论】:

    • 你可能想提一下,indexer 不能像数组那样用于向列表中添加新项目,它只能用于修改现有项目。即var list = new List&lt;int&gt;(10); list[0] = 10; 将抛出 IndexOutOfRange 异常
    猜你喜欢
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    相关资源
    最近更新 更多