添加新对象时列出覆盖先前添加的对象

时间:2018-12-23 03:46:14

标签: c# list

我正在遍历正在制作的程序的某些逻辑,该程序通过.txt文件读取文本,每次到达算法添加了创建的类对象的位置时,它都会起作用,但是下次击中前一个对象,将其数据更改为当前正在添加的对象,依此类推。

这是前言的代码片段,它位于While循环内,并嵌套在3个if语句中。

问题:为什么它会覆盖所有其他条目?

我的逻辑是100%正常工作,我对它进行了10个小时的测试,有很多断点,也请放轻松,我精通C#

    if (Att == a1)
    {
        Student s1 = new Student();
        s1.Eid = Eid;
        s1.Name = Name;
        s1.Attempt1 = att1;
        AllStudents.Add(s1);
        //AllStudents.Add(new Student(Eid,Name, att1));

        Eid = line;
        Att = "";
        qnum = 1;
        counter = 1;
    }

这是我的学生班

public class Student
    {
        public string Eid { get; set; }
        public string Name { get; set; }
        public string[] Attempt1 { get; set; }
        public string[] Attempt2 { get; set; }
        public string[] Attempt3 { get; set; }
        public string[] Att1filler = { "n/a", "n/a", "n/a", "n/a", "n/a", "n/a" };
        public string[] Att2filler = {"n/a","n/a","n/a","n/a","n/a","n/a"};
        public string[] Att3filler = {"n/a","n/a","n/a","n/a","n/a","n/a"};

        public int FinalGrade { get; set; }
        public int Grade1 { get; set; }
        public int Grade2 { get; set; }
        public int Grade3 { get; set; }
        public int Grade4 { get; set; }

        public Student()
        {
            FinalGrade = 0;
            Attempt1 = Att1filler;
            Attempt2 = Att2filler;
            Attempt3 = Att3filler;
        }
        public Student(string Eagid, string name, string[] Att1)
        {
            Eid = Eagid;
            Name = name;
            Attempt1 = Att1;
            Attempt2 = Att2filler;
            Attempt3 = Att3filler;
            FinalGrade = 0;
        }
        public Student(string Eagid, string name, string[] Att1, string[] Att2)
        {
            Eid = Eagid;
            Name = name;
            Attempt1 = Att1;
            Attempt2 = Att2;
            Attempt3 = Att3filler;
            FinalGrade = 0;
        }
        public Student(string Eagid, string name, string[] Att1, string[] Att2, string[] Att3)
        {
            Eid = Eagid;
            Name = name;
            Attempt1 = Att1;
            Attempt2 = Att2;
            Attempt3 = Att3;
            FinalGrade = 0;
        }
}

最后这就是我声明我的列表的方式

 public List<Student> AllStudents = new List<Student>();

AllStudents.add(new Student(Eid,Name, att1));也是我发现对我仍然无效的另一种解决方案。

1 个答案:

答案 0 :(得分:0)

我知道了。吸取了关于通过引用传递与通过值传递的课程。请确保您的算法是否在循环,以便在循环内使用new初始化并在循环内使用的所有内容都重新初始化,以免您不只是为每个对象传递相同的引用。(很抱歉,如果答案不是100 %我要花2个小时才能尝试完成此项目!)