在列表中添加元素会抛出 ArgumentOutOfRangeException

adding element in a list throws ArgumentOutOfRangeException

我的代码抛出这个:

ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index error

当它在列表中找到计数小于特定数字的元素时。关于如何更正代码的任何想法?

我在各处添加了 debug.log 代码来确定错误发生的确切位置,因为 Visual Studio.

没有下划线的错误
List<int> emptyRows = new List<int>();
for (int j = 0; j < gridPositions.Count; j++) // try to find if a row is still empty
                {
                    Debug.Log("gridPositions[" + j + "].Count is " + gridPositions[j].Count);
                    Debug.Log("columns are" + columns);
                    if (gridPositions[j].Count == columns)
                    {
                        Debug.Log("trying to add to emptyrows");
                        emptyRows.Add(j);
                        Debug.Log("added to emptyrows and its count is " + emptyRows.Count);
                    }
                    else
                    {
                        Debug.Log("found an occupied row at row " + j);
//ERROR STRIKES HERE
                    }
                    Debug.Log("emptyRows is " + emptyRows[j]);
                    Debug.Log("emptyRows count is " + emptyRows.Count);
                }

我希望 emptyRows 跟踪并记录所有未占用的行,但是当它填充占用的行时,它不会继续执行 for 循环并停止。

如果 (gridPositions[j].Count == columns)

,您只添加到 emptyRows

但是您正在访问 emptyRows[j] 的每个值 j

所以 emptyRows 最终拥有的项目少于 j 的值