错误:索引超出数组范围

时间:2014-04-23 04:54:53

标签: c# arrays indexoutofboundsexception

 string[] lines = System.IO.File.ReadAllLines(@"C:\Users\myname\Desktop\test.txt");
        int cnt = lines.Count();

        int arraynum1 = 0;
        int arraynum2 = 1;
        int arraynum3 = 2;

        try
        {
            for (int x = 0; x < cnt; x++)
            {
                mc[0] = lines[arraynum1];
                mc[1] = lines[arraynum2];
                mc[2] = lines[arraynum3];

                arraynum1 = arraynum3 + 1;
                arraynum2 = arraynum3 + 1;
                arraynum3 = arraynum3 + 1;

                ListViewItem item = new ListViewItem(new[] { mc[0], mc[1], mc[2] });
                listView1.Items.Add(item);

            }

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

每当我在cnt中使用变量for loop来指定要停止的行时,我会收到此问题标题中列出的错误,但每当我设置integer时在循环中代替cnt它可以完美地运作。

3 个答案:

答案 0 :(得分:4)

不应该

    arraynum1 = arraynum1 + 1;
    arraynum2 = arraynum2 + 1;
    arraynum3 = arraynum3 + 1;

而不是

    arraynum1 = arraynum3 + 1;
    arraynum2 = arraynum3 + 1;
    arraynum3 = arraynum3 + 1;

答案 1 :(得分:2)

试试这个:

arraynum1 = arraynum1 + 1;
arraynum2 = arraynum2 + 1;
arraynum3 = arraynum3 + 1;

因为你目前在所有三种情况下都指的是同一阵列arraynum3。

arraynum1 = arraynum3 + 1;
arraynum2 = arraynum3 + 1;
arraynum3 = arraynum3 + 1;

答案 2 :(得分:2)

假设你的文件包含6行,这就是你的mc [0] .. mc [2]在你的for循环中保存的值:

迭代1(x = 0):

mc[0] = lines[0]
mc[1] = lines[1]
mc[2] = lines[2]

迭代2(x = 1):

mc[0] = lines[3]
mc[1] = lines[3]
mc[2] = lines[3]

迭代3(x = 2):

mc[0] = lines[4]
mc[1] = lines[4]
mc[2] = lines[4]

迭代4(x = 3):

mc[0] = lines[5]
mc[1] = lines[5]
mc[2] = lines[5]

迭代5(x = 4):

The exception you stated will be thrown here
mc[0] = lines[6]
mc[1] = lines[6]
mc[2] = lines[6]

迭代6(x = 5):     永远不会到达

因此,不要将循环var x增加1,而是将其增加3,如:

        for (int x = 0; x+2 < cnt ; x+=3)
        {
            mc[0] = lines[x];
            mc[1] = lines[x+1];
            mc[2] = lines[x+2];

            ListViewItem item = new ListViewItem(new[] { mc[0], mc[1], mc[2] });
            listView1.Items.Add(item);

        }

此方法还会考虑您的文件不包含不能被3分割的行数的可能性。