通过2维数组C#迭代 [英] Iterate through 2 dimensional array c#
问题描述
for(int k=0;k <= odds.GetLength(-1);k++)
code的上面一行是应该通过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.
推荐答案
正在传递一个无效的指数<一个href=\"http://msdn.microsoft.com/en-us/library/system.array.getlength.aspx\"><$c$c>GetLength$c$c>.多维数组的尺寸是 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];
这篇关于通过2维数组C#迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!