理解和解决” .NET”索引超出范围错误
> 当您尝试使用无效索引中访问集合中的项目(例如数组或列表)中时,出现了.net中出现的“ indexoutofrangeException”。 因为.NET集合为零索引,因此有效的索引范围为0到(长度-1)。 试图访问超出此范围的元素(使用负数等于或大于长度的索引)触发此例外。让我们用一个数组示例说明:
int[] numbers = new int[5]; // Array with 5 elements (indices 0-4) Console.WriteLine(numbers[5]); // Throws IndexOutOfRangeException
尝试访问不存在的第六个元素,从而导致错误。numbers[5]
>
与其他集合一起工作
此基于零的索引适用于其他集合,包括。 最后一个可访问的元素始终处于indexList<T>
。
Count - 1
为了安全迭代,请考虑使用A
for
List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; for (int i = 0; i < names.Count; i++) { Console.WriteLine(names[i]); }
foreach
foreach (string name in names) { Console.WriteLine(name); }
避免以下例外:
>
Length - 1
Count - 1
使用Count
>属性(用于列表)或Length
属性(用于数组)来确定集合的大小。
Count
Length
>首选foreach
循环简化迭代并消除了手动索引错误的风险。
foreach
try-catch
>
IndexOutOfRangeException
以上是为什么我的代码中会遇到'索引之外的范围”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!