问题描述
异常的更多细节:索引超出范围。必须是非负数,小于集合的大小。参数名称:index
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
在调试时,我可以在Visual Studio提供的表中看到,我的model.Meshes.Count是5,而在当前的迭代中,索引是1.索引小于我的集合的大小,负。
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.
提前感谢
推荐答案
您需要使用列表。添加(...)而不是索引。
You need to use list.Add(...) instead of indexing.
列表的大小为0,您可以添加项目,但是您编码索引不存在的项目。即使在index = 0,也将失败。
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.
这篇关于ArgumentOutOfRangeException未处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!