错误:索引超出了数组的范围。

我知道问题是什么,但我很困惑我的程序如何输出一个超出数组的值。

我有一个0到8的整数,这意味着它可以保持9个整数,对吗? 我有一个int,检查以确保用户输入值是1-9。 我从整数中删除一个(像这样)

if (posStatus[intUsersInput-1] == 0) //if pos is empty { posStatus[intUsersInput-1] += 1; }//set it to 1 

然后我自己输入9并得到错误。 它应该访问数组中的最后一个int,所以我不明白为什么我会收到错误。 相关代码:

 public int[] posStatus; public UsersInput() { this.posStatus = new int[8]; } int intUsersInput = 0; //this gets try parsed + validated that it's 1-9 if (posStatus[intUsersInput-1] == 0) //if i input 9 it should go to 8? { posStatus[intUsersInput-1] += 1; //set it to 1 } 

错误:

 "Index was outside the bounds of the array." "Index was outside the bounds of the array." 

您已声明一个可以存储8个元素而不是9个元素的数组。

 this.posStatus = new int[8]; 

这意味着postStatus将包含索引0到7的8个元素。

 public int[] posStatus; public UsersInput() { //It means postStatus will contain 9 elements from index 0 to 8. this.posStatus = new int[9]; } int intUsersInput = 0; if (posStatus[intUsersInput-1] == 0) //if i input 9, it should go to 8? { posStatus[intUsersInput-1] += 1; //set it to 1 } 

//如果我输入9它应该是8?

您仍然需要使用数组的元素。 循环遍历数组时,您将计算8个元素,但它们仍将是数组(0) – 数组(7)。

  string dob1 = drUserInfo["dtpDateOfBirth"].ToString(); DateTime dtt = DateTime.ParseExact(dob1, "MM-dd-yyyy", CultureInfo.InvariantCulture); string date = dtt.ToString("yyyy-MM-dd"); txtDOB.Text = date;