【问题标题】:ArgumentOutOfRangeException Was UnhandledArgumentOutOfRangeException 未处理
【发布时间】:2011-09-20 04:18:05
【问题描述】:

异常的更多细节:索引超出范围。必须是非负数且小于集合的大小。参数名称:索引

阅读异常时,我明白它试图告诉我什么。我不明白的是-为什么-它会出现。以下是相关代码的sn-p:

        //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。Index小于我的集合的大小,它是非负的。

是什么引发了异常?我已经尝试搜索类似的示例,但还没有找到任何可以完全回答我的问题的东西。

提前致谢。

【问题讨论】:

  • 你可以写成var spheres = model.Meshes.Select(m =&gt; m.BoundingSphere).ToList();var spheres = (from m in model.Meshes select m.BoundingSphere).ToList();

标签: c# exception xna


【解决方案1】:

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

列表的大小默认为0,您可以添加项目,但您编写索引不存在的项目。即使在 index = 0 上它也会失败。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-26
        • 2023-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多