为什么我让index超出了范围

本文关键字:范围 index 为什么 | 更新日期: 2023-09-27 18:01:23

所以我有一个包含9个元素的列表,但是当我试图在"右"列表中添加数组[4]元素时,我得到了一个超出范围错误的索引。谁能告诉我怎么了?

public static int dosomething(ref List<int> array, int n) 
{
    List<int> left = new List<int>();
    List<int> right = new List<int>();
    for (int i = 0; i < n; i++) 
    {
        if (i < n/2) 
        {
            left.Add(array[i]);
            Console.WriteLine("Left[{0}] = {1}", i, left[i]);
        } 
        else 
        {
            Console.WriteLine("i = {0}", i);
            right.Add(array[i]);
            Console.WriteLine("Right[{0}] = {1}", i, right[i]);
        }
    }
}

为什么我让index超出了范围

您为leftright使用了错误的索引。由于您正在遍历数组,并且在某些时间添加left,在其余时间添加right,因此您不能使用i作为检索值的索引。错误实际上是发生在你的Console.WriteLine()调用。

你可以使用:

left[left.Count - 1];

或:

right[right.Count - 1];