簡體   English   中英

C#數組索引錯誤

[英]C# Array Index Error

我要添加的簡單數組,但是不斷出現“索引越界”錯誤。 環顧四周,無法完全弄清楚我要去哪里,我認為這與我使用pos變量的地方有關。 發表任何我認為可能相關的內容。 提前致謝。

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
    }

Array.FindIndex將根據謂詞返回位置,如果匹配的項均不返回-1 ,對於您的情況,您將在數組中分配數組的每個元素

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

這將確保沒有任何項目為null,因此從Array.FindIndex返回-1 ,隨后在您使用該位置pos訪問數組元素時,您將獲得異常。

這行:

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

在執行以下操作時, pos設置為-1

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

您將獲得例外。

您可以使用實例化的Account對象初始化數組。

不能保證FindIndex()調用將返回有效位置(即pos將被分配為-1)

之后,您可以參考db [-1],這將引發異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM