c# - 错误 : Index was outside the bounds of the array.

标签 c# arrays indexing bounds

<分区>

我知道问题在说明什么,但我对我的程序如何输出数组外的值感到困惑。

我有一个 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 个元素。

关于c# - 错误 : Index was outside the bounds of the array.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21700879/

相关文章:

c# - 用C#弹吉他

javascript - 使用 For 循环不显示列表

PhP:合并具有匹配键的数组并删除/删除额外的不匹配值

rindexOf 方法的 Swift 2/3 String 实现

c# - 如何使用 MS VC# 2008 EE 为 Fiddler 创建工作扩展 dll?

c# - WPF ComboBox 绑定(bind)到 List<string>

java - 如何从数组中获取唯一项?

ruby-on-rails - 为什么 add_index 使用 'gin' 而不是创建 'btree' 索引?

algorithm - 快速点索引-(> 100.000.000)-in-polygon-(> 10.000)-test

c# - 如何防止空格被修剪?