【发布时间】: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 循环中。