ArgumentOutOfRangeException未处理

时间:2011-09-20 04:18:05

标签: c# exception xna

例外的进一步细节:指数超出范围。必须是非负数且小于集合的大小。参数名称:index

在阅读例外情况时,我理解它试图告诉我的内容。我不明白的是 - 为什么它会出现。以下是相关代码的片段:

        //the model contains more than one mesh, so each
        //one must be accounted for in the final sphere
        List<BoundingSphere> spheres = new List<BoundingSphere>();
        int index = 0;

        //cycle through the meshes
        foreach (ModelMesh mesh in this.model.Meshes)
        {
            //and grab its bounding sphere
            spheres[index++] = mesh.BoundingSphere; //<- this is the line that throws the exception
        } //end foreach

在调试时,我可以在Visual Studio提供的表中看到我的model.Meshes.Count是5,而在当前迭代中,index是1.索引小于我的集合的大小,它是非负。

什么引发了例外?我试过寻找类似的例子,但还没有发现任何可以回答我的问题。

提前致谢。

3 个答案:

答案 0 :(得分:3)

您需要使用list.Add(...)而不是索引。

deafult的列表大小为0,您可以添加项目,但您可以编码索引不存在的项目。它甚至会在index = 0时失败。

答案 1 :(得分:1)

您需要使用Add方法来增加列表的大小。因此,请尝试spheres.Add(mesh.BoundingSphere);而不是spheres[index++] = mesh.BoundingSphere;

答案 2 :(得分:1)

你打算写spheres.Add(mesh.BoundingSphere)。创建后,spheres列表为空。您无法访问不存在的项目。

相关问题