我正在添加的简单数组,但是我不断收到此索引超出界限错误。环顾四周,无法弄清楚我要出错的地方,我假设这与我使用pos变量的地方有关。发布我认为可能相关的任何内容。提前致谢。C#数组索引错误
const int MAX = 5;
Account[] db = new Account[MAX];
// global variable for position in array
int pos;
private void Form1_Load(object sender, EventArgs e)
{
// initialise the array with instantiated objects
for (int i = 0; i < MAX; i++)
db[i] = new Account();
}
private void OpenAcc_Click(object sender, EventArgs e)
{
//hide menu
hide_menu();
//make new form elements visible
tbNameEnt.Visible = true;
tbBalaEnt.Visible = true;
SubDet.Visible = true;
//set pos to the first empty element of array
pos = Array.FindIndex(db, i => i == null);
}
private void SubDet_Click(object sender, EventArgs e)
{
string textBox1;
double textBox2;
int a = 0011228;
int b = pos + 1;
int accNo;
//get and parse input details
textBox1 = tbNameEnt.Text;
textBox2 = double.Parse(tbBalaEnt.Text);
//allocate account number
accNo = int.Parse(a.ToString() + b.ToString());
//set details for new object in array
db[pos].SetAccount(textBox1, accNo, textBox2); //ERROR HERE
//print account created confirmation message
ConfMess();
//OK button then takes us back to menu
}
它究竟发生了什么? – zerkms
改为使用'List'。 –
“第一个空元素”不存在,因为您在Form_Load中设置了所有值,因此没有空条目,所以pos为-1或某物。 – Ted