【问题标题】:Error: (using List class) Index was outside the bounds of array错误:(使用 List 类)索引超出了数组的范围
【发布时间】:2016-06-16 06:23:10
【问题描述】:

我正在做一个项目,我是 C# 编程的初学者,不知何故有一个我无法解决的问题。发生原因:在执行代码时,应用程序成功启动但出现异常 表明“索引超出了数组的范围”。之后,我能够单击列表框上的项目,并在文本框中显示第二个对象。所以......它似乎有效(单击列表框的项目)但我无法弄清楚为什么它会引发关于数组的异常。下面是我拥有的当前代码。

**更新:我真诚地道歉。我上传了错误的代码。应该是这样的代码:

代码:

struct studentInfo
{  
  public string studentID;
  public string major;
}  

public partial class Form1 : Form
{
    private List<studentInfo> studentList = new List<studentInfo>();

    public Form1()
    {
        InitializeComponent();
    }


    private void ReadInputFile()
    {
        try
        {
            StreamReader inputFile;
            string line = "";

            studentInfo student = new studentInfo();

            char[] delimiter = { ',' };

            inputFile = File.OpenText("Student Info.txt");

            while (!inputFile.EndOfStream)
            {
                line = inputFile.ReadLine();

                string[] token = line.Split(delimiter);

                student.studentID = token[0];
                student.major = token[1];

                studentList.Add(student);

            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    private void DisplaystudentID()
    {
        foreach (studentInfo student in studentList)
        {
            studentInfoListBox.Items.Add(student.studentID);
        }
    }

    private void DisplayNames()
    {

    }
    private void button1_Click(object sender, EventArgs e)
    {
        ReadInputFile();

        DisplaystudentID();
    }

    private void studentInfoListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = studentInfoListBox.SelectedIndex;

        majorTextBox.Text = studentList[index].major;


    }

    private void button3_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }
}

【问题讨论】:

  • 它在哪一行抛出异常以及异常的确切类型和消息是什么?
  • 也许其中一行没有逗号?例如,文件中的最后一行,是最后一行 with 文本,还是那里可能有一个空行?
  • 您好!它抛出异常的那一行是 catch 语句。带有 MessageBox 的 catch 语句。异常消息如下所示:“无法评估表达式,因为本机表达式位于调用堆栈的顶部”。
  • 附带说明,您只是为您的 while 子句创建了一个 PhoneBookEntry 对象。这样,您最终会一次又一次地将单个对象添加到phoneList,但引用永远不会改变。这样,您最终将得到一个列表,其中包含 while 循环的相同(最后一个)条目。将 PhoneBookEntry entry = new PhoneBookEntry(); 行放在 while 循环中。

标签: c# arrays


【解决方案1】:

我的猜测是 SelectedIndexChanged 在开始时运行(在您选择任何内容之前),此时 nameListBox.SelectedIndex 将为 -1,您无法在列表中获得“负 1 位置的项目”。我会确保所选索引有效

https://msdn.microsoft.com/fr-fr/library/system.windows.forms.listbox.selectedindex(v=vs.110).aspx "当前选中项的从零开始的索引。如果没有选中项,则返回负一 (-1) 值。"

我会这样更改代码:

private void nameListBox_SelectedIndexChanged(object sender, EventArgs e)
{
    int index = nameListBox.SelectedIndex;
    if(index !=-1)
    {
        phoneLabel.Text = phoneList[index].phone;
    }
    // else do nothing, the selected item didn't really change, it's just called for the first time, think of it as the control saying "hey i just got created and i'm notifying you that the selected item is now nothing"
}

【讨论】:

  • 谢谢你,罗南~我明白这个逻辑是如何工作的。作为我的 c# 编程教育的一部分,我会记下这一点。 :D
【解决方案2】:

你必须保护SelectedIndex,当控件最初创建时SelectedIndex设置为-1

private void nameListBox_SelectedIndexChanged(object sender, EventArgs e)
{
    if(nameListBox.SelectedIndex >=0)
    {
         int index = nameListBox.SelectedIndex;

         phoneLabel.Text = phoneList[index].phone;
    } 
}

【讨论】:

  • 没问题。很高兴这对您有所帮助。
  • nameListBox.SelectedIndex == -1 是典型的,当没有选择项目时。
【解决方案3】:

您的程序中唯一的数组处理是这样的:

entry.name = tokens[0];
entry.phone = tokens[1];

因此原因是你的文本文件中的一行没有逗号,所以tokens 没有两部分。

一个常见的原因是文件在最后的 real 条目之后有一个换行符,因此最后一行是空行。

我会在这里简单地处理这个:

if (tokens.Length < 2)
    continue;

【讨论】:

    【解决方案4】:

    您没有让我们知道异常发生的确切位置,但我认为它可能在这部分

    line = inputFile.ReadLine();
    
    string[] tokens = line.Split(delim);
    
    entry.name = tokens[0];
    entry.phone = tokens[1];
    

    如果您的行是空的或没有“,”,您将在下一行得到异常

    您还需要检查nameListBox_SelectedIndexChangedindex 位置的访问列表。

    【讨论】:

      【解决方案5】:

      当您尝试访问列表中未退出的元素时,会发生“索引超出数组范围”异常。当您单击列表中的最后一项时,我相信您会遇到此异常。

      在您的 nameListBox_SelectedIndexChanged 方法中,您是以下之一。

      int index = nameListBox.SelectedIndex -1;
      

      phoneLabel.Text = phoneList[index-1].phone;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-18
        • 1970-01-01
        • 2017-10-20
        • 2014-03-09
        • 2013-12-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多