2014-02-26 83 views
2

我正在添加的简单数组,但是我不断收到此索引超出界限错误。环顾四周,无法弄清楚我要出错的地方,我假设这与我使用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 
    } 
+1

它究竟发生了什么? – zerkms

+0

改为使用'List '。 –

+0

“第一个空元素”不存在,因为您在Form_Load中设置了所有值,因此没有空条目,所以pos为-1或某物。 – Ted

回答

4

Array.FindIndex会,根据谓词返回的位置,如果没有比它匹配的项目将在

for (int i = 0; i < MAX; i++) 
     db[i] = new Account(); 

这将返回-1,对于你的情况,你是分配阵列中的每个元素确保没有项目为空,因此从Array.FindIndex返回-1,稍后当您使用该位置pos访问数组元素时,您将得到异常。

这条线:当你做

pos = Array.FindIndex(db, i => i == null); 

会设置pos-1后来:

db[pos].SetAccount(textBox1, accNo, textBox2); 

您将得到异常。

0

您使用实例化的Account对象初始化您的数组。

有没有保证FindIndex()调用会返回一个有效的位置(即POS机将被分配-1)

在此之后,你可能指的是DB [-1],这将引发异常。