【问题标题】:Error on using For loop to add to list of lists (ArgumentOutOfRangeException)使用 For 循环添加到列表列表时出错 (ArgumentOutOfRangeException)
【发布时间】:2013-02-13 06:19:08
【问题描述】:

这里是第一个计时器。 StackOverflow 帮助我在一定程度上了解了数组和列表,但我遇到了一个在其他地方没有得到解答的问题。

目标:获取一个现有的多维数组,读取每一行,如果它以正确的标识符开头,则将该行拉入一个列表。每个列表都成为我列表的一部分。

问题:如果我使用 newGrid[0].Add(CSVReader.grid[x,y]);在它下面运行良好。但是如果我使用 [y] 而不是 [0] 我会得到一个异常。在我遇到异常时,y = 0 不是吗?我想使用 for 循环的 y 使从数组中拉出的每一行都成为一个新列表。

    public void processCSV () {

    List<List<string>> newGrid = new List<List<string>>();

    for (int y = 0; y < CSVReader.grid.GetUpperBound(1); y++) {
        if (CSVReader.grid[0,y] == "T1") {
            newGrid.Add(new List<string>());
            for (int x = 0; x < CSVReader.grid.GetUpperBound(0); x++) {
                newGrid[y].Add(CSVReader.grid[x,y]);    
            }
            foreach(string item in newGrid[y]) {    
                print(item);
            }

        }
    }
}

【问题讨论】:

  • 因为 newGrid.Add(new List());在 IF 语句中,y 不一定与您列表中的项目数相对应。这可能是您的问题吗?

标签: c# list unity3d


【解决方案1】:

newGrid 中的行号与CSVReader.grid 中的行号不匹配,因为您仅从源数组中复制了一些行。

每次调用newGrid.Add 时,请使用单独的变量来计算newGrid 中的行数,或者只是将元素添加到最后一行,而不是重复使用y。

【讨论】:

  • 是的,你是对的——谢谢!希望我能投票,但显然我需要先获得一些声誉;)
猜你喜欢
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-24
相关资源
最近更新 更多