我在form1上有一个按钮来执行此操作:
private void button1_Click(object sender, EventArgs e)
{
int numberOfStudentsInClass;
if (!int.TryParse(txtBoxNoS.Text, out numberOfStudentsInClass))
{
MessageBox.Show("Please enter the number of students in the class", "Alert", MessageBoxButtons.OK);
return;
}
_allStudentsArray = new Student[numberOfStudentsInClass];
form3.Show();
form3.lblClass.Text = string.Format("Class {0}", comboBox1.Text);
form3.lblNoOfS.Text = numberOfStudentsInClass.ToString();
}
form3正确地将正确的整数和字符串传递给此函数:
public void addStudent(string sn, string tp, string tw, string gc, string gp, string gg, string t, string n)
{
int sni = int.Parse(sn) - 1;
_allStudentsArray[sni] = new Student();
_allStudentsArray[sni].studentNumber = int.Parse(sn);
_allStudentsArray[sni].topics = tp;
_allStudentsArray[sni].testWeek = tw;
_allStudentsArray[sni].gradeContent = int.Parse(gc);
_allStudentsArray[sni].gradePrn = int.Parse(gp);
_allStudentsArray[sni].gradeGrammar = int.Parse(gg);
_allStudentsArray[sni].total = int.Parse(t);
_allStudentsArray[sni].notes = n;
}
在名称空间的开头我有:
public class Student
{
public int studentNumber;
public string topics;
public string testWeek;
public int gradeContent;
public int gradeGrammar;
public int gradePrn;
public int total;
public string notes;
public int studentsInClass;
public int lastTestWeek;
}
Student[] _allStudentsArray;
但是一旦我尝试分配_allStudentArray[sni].studentNumber = sn
,我就会收到一个null异常错误。我已经阅读了关于null异常的非常详细的答案,我认为它来自数组未正确初始化。但是连续两天我都无法找出原因。