遍历二维数组 c# [英] Iterate through 2 dimensional array c#
问题描述
for(int k=0;k <= odds.GetLength(-1);k++)
上面的代码行应该遍历一个 Double 类型的二维数组,但不断抛出以下异常.索引超出范围异常.有人愿意解释原因并提供解决方案吗?非常感谢.
The above line of code is supposed to iterate through a two dimensional array of type Double but keeps throwing the following exception. Index Out Of Range Exception. Would someone be kind enough to explain why and provide a solution. Many thanks.
推荐答案
您正在将无效索引传递给 GetLength
.多维数组的维数是基于 0
的,所以 -1
无效,使用负数(或大于维数 - 1 的数字)会导致 IndexOutOfRangeException
.
You are passing an invalid index to GetLength
. The dimensions of a multidimensional array are 0
based, so -1
is invalid and using a negative number (or a number that is larger than the number of dimensions - 1) would cause an IndexOutOfRangeException
.
这将遍历第一维度:
for (int k = 0; k < odds.GetLength(0); k++)
您需要添加另一个循环来遍历第二个维度:
You need to add another loop to go through the second dimension:
for (int k = 0; k < odds.GetLength(0); k++)
for (int l = 0; l < odds.GetLength(1); l++)
var val = odds[k, l];
这篇关于遍历二维数组 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!