我有一个获取文件StudentMarks.dat的代码,并输出所有studentID,assessment,marksachieved,maxMarks。但是我能够拆分所有值但无法将它们添加到我的列表中并抛出null异常。请帮忙。我的代码如下:
struct StudentGrade
{
public string StudentID { get; set; }
public string AssessmentID { get; set; }
public string MaxGrade { get; set; }
public string GradeAchieved { get; set; }
}
private List<StudentGrade> _studentGrade;
private void loadItemsFromFiles()
{
string record = string.Empty;
string filePath = "StudentMarks.dat";
FileStream stream = new FileStream(filePath,FileMode.Open);
StreamReader reader = new StreamReader(stream);
dgvGrades.Columns.Add("StudentID", "Student Id");
dgvGrades.Columns.Add("Assessment", "Assessment");
dgvGrades.Columns.Add("MarksAchieved", "Marks Achieved");
dgvGrades.Columns.Add("MaxMarks", "Max Marks");
try
{
while ((record = reader.ReadLine()) != null)
{
string[] field = record.Split(',');
StudentGrade grade = new StudentGrade()
{
StudentID =field[0].ToString(),
AssessmentID = field[1].ToString(),
MaxGrade = field[2].ToString(),
GradeAchieved = field[3].ToString()
};
_studentGrade.Add(grade);
}
}
catch (IOException exception)
{
throw exception;
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}
答案 0 :(得分:1)
你还没有初始化你的列表,它是null,所以你得到了例外。
private List<StudentGrade> _studentGrade = new List<StudentGrade>();
在C#中声明一个类变量时,它会获得它的类型的默认值。例如,int
默认值为0
,bool
默认值为“false”。所有引用类型的默认值均为“null”。因此,当您使用它们而不初始化它们时,您会得到NullReferenceException
。
答案 1 :(得分:1)
您需要在使用
之前初始化您的收藏private List<StudentGrade> _studentGrade = new List<StudentGrade>();