ArgumentOutOfRangeException Was Unhandled

蹲街弑〆低调 提交于 2019-12-13 04:41:59

问题


Further details of the exception: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

When reading the exception, I understand what it's trying to tell me. What I don't understand is -why- it's coming up. Here is the snippet of relevant code:

        //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

While debugging, I can see in the table provided by Visual Studio that my model.Meshes.Count is 5, and that at the current iteration, index is 1. Index is less than the size of my collection, and it is non-negative.

What's throwing the exception? I've tried searching for similar examples, but haven't found anything to quite answer my question yet.

Thanks in advance.


回答1:


You need to use list.Add(...) instead of indexing.

List's size is 0 by deafult and you can add items, but you code indexing non-existent item. It will fail even on index = 0.




回答2:


You meant to write spheres.Add(mesh.BoundingSphere). Your spheres list is empty after you created it. You cannot access an item which is not there.




回答3:


You need to use the Add method to increase the size of the list. So try spheres.Add(mesh.BoundingSphere); rather than spheres[index++] = mesh.BoundingSphere;



来源:https://stackoverflow.com/questions/7480087/argumentoutofrangeexception-was-unhandled

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!