【问题标题】:I have a loop on C# in array but it does not work as well [duplicate]我在数组中的 C# 上有一个循环,但它不能正常工作 [重复]
【发布时间】:2017-07-16 06:19:54
【问题描述】:

这是我现在得到的错误:

for(int i = 0; i < arrDate.Length; i++)
{
    Console.WriteLine(arrDate[i, 0]);            
}

错误消息是:索引超出范围异常未处理。

这是数组:

string[,] arrDate = new string[2, 3];
arrDate[0, 0] = "10/05/2017";
arrDate[0, 1] = "15/05/2017";
arrDate[0, 2] = "mily";
arrDate[1, 0] = "20/05/2017";
arrDate[1, 1] = "22/05/2017";
arrDate[1, 2] = "many";

这个问题与this question不同

【问题讨论】:

  • 显示您是如何声明和初始化该 arrDate 变量
  • 亲爱的史蒂夫我已经添加了它

标签: c#


【解决方案1】:

多维数组的Length 属性给出了元素的总数。想象一下你有一个二维的 2 x 3,然后长度返回 2 x 3 = 6。

您的代码尝试迭代大约 6 行(在此示例中),并在尝试访问第三行时引发异常 (i = 2)。

请尝试

for(int i = 0; i < arrDate.GetLength(0); i++)
{
    Console.WriteLine(arrDate[i, 0]);            
}

GetLength(0) 返回第一个维度的长度。

【讨论】:

  • 感谢它现在对我有用
猜你喜欢
  • 2011-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2015-12-27
  • 2015-05-14
  • 1970-01-01
  • 2014-10-07
相关资源
最近更新 更多