指数数组的边界之外。怎么能解决这个问题 [英] Index was outside the bounds of the array. how can solve this problem
问题描述
public string[,] getday()
{
string[,] monn = new string[31, 1];
DateTime now = DateTime.Now;
for (int i = 0; i < 31; i++)
{
int j = i + 1;
monn[i, 0] = j.ToString();
monn[i, 1] = j.ToString();
}
return monn;
}
rotected void Page_Load(object sender, EventArgs e)
{
string[,] day = objUtility.getday("EN");
response.write(day[i, 1]);
}
此代码显示此错误:System.IndexOutOfRangeException:索引超出了数组的范围。
我怎么能解决这个问题??
This code show this error: System.IndexOutOfRangeException: Index was outside the bounds of the array.
how can i solve this problem??
推荐答案
你的数组定义如下:
Your array definition looks like this:
string[,] monn = new string[31, 1];
这意味着最高秒index是 0
,因为 1
是长度。但是,在 for
循环中,您使用 1
作为第二个索引,它超出了数组的范围,因为最高的第二个索引是 0
:
This means that the highest second index is 0
, because 1
is the length. However, inside your for
loop, you are using 1
as second index which is outside the bounds of the array because the highest second index is 0
:
monn[i, 0] = j.ToString();
monn[i, 1] = j.ToString();
所以,你有用替换
以确保最高的第二个索引是新字符串[31,1]
新字符串[31,2] 1
,这可以避免错误。
So, you have to replace new string[31, 1]
with new string[31, 2]
to make sure the highest second index is 1
, which avoids the error.
new string[31, 1]
括号中的数字是特定维度中元素的数量,因此在第二个维度中您有1个元素,但您尝试索引2 - 索引为0的索引1和索引1的索引...
括号中的数字再次是元素的数量,因此最大索引将是数字减1 - 在您的情况下为0,什么意味着索引1超出范围!
The numbers in the bracket are the number of the elements in the specific dimension, so in the second dimension you have 1 lement, but you try to index two - one with index 0 and one with index 1...
Again the numbers in the bracket are the number of the elements, so the max index will be the number minus 1 - in your case 0, what means that index 1 is out of range!
这篇关于指数数组的边界之外。怎么能解决这个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!