对于我的中级 C# 类,我的任务是在通过文件流连接到程序的 .txt 文件中提取和维护数据。我对编码的理解都是正确的,但是当表单加载时,它并没有提取数据。我已经从我能想到的各个角度对其进行了故障排除,但我不知道自己在哪里。我将在下面包含相关的代码位,但我有一个类,其中包含专门用于处理文件流和数据填充的方法,以及一个用于“学生对象”的类。
这是我试图读取的 .txt 文件中的数据
杰夫·迪克森|100|97|68
莎朗·博德里|95|76|87
哈莉纽珀特|95|89|94
这是我在 StudentDB 类中从源文件中提取的方法
public static List<Student> GetStudents()
{
//Creates a new list to be returned
List<Student> students = new List<Student>();
//Creates a new file stream to read the data
StreamReader filler = new StreamReader(new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));
//Starts the fill loop
while(filler.Peek() != -1)
{
string row = filler.ReadLine();
//Creates an array to fill with the line, deliniated by the pipe
string[] columns = row.Split('|');
//Creates an instantiation of the Student Class to use for filling purposes
Student student = new Student();
//Adds the student name from the array to the Student Object
student.Name = columns[0];
//Creates a loop that will go through the string array and pull the scores to add to the list
//Converting them to integer in the process
for (int i = 1; i < columns.Length; i++)
{
student.Scores.Add(Convert.ToInt32(columns[i]));
}
//Adds the instance of the student object to the list
students.Add(student);
}
//Closes the stream and returns the list
filler.Close();
return students;
这是具有属性和方法的学生类:
public class Student
{
//General Constructor
public Student()
{ }
//Public Properties
public string Name
{
get;
set;
}
public List<int> Scores
{
get;
set;
}
public string GetDisplayText()
{
string total = "";
foreach (int score in Scores)
{
total += "|" + score;
}
return Name + total;
}
}
这是我用每个学生项目填充列表框的方法:
//Program wide variable for a list of students
public List<Student> students = null;
//Method to fill the list box
private void FillBox()
{
//Clears the list box in order to allow for the data to be entered
lstStudents.Items.Clear();
//Fills the students list variable using the method from studentDB class
students = studentDB.GetStudents();
//Cycles throught the list and fills the list box
foreach(Student s in students)
{
lstStudents.Items.Add(s.GetDisplayText());
}
}