如何在C#中填充类中的列表?

时间:2018-03-11 11:45:13

标签: c# list class

我试图了解嵌套类型,但即使在检查了几个网站后,我仍然无法理解它。我有一个列表在课堂上。我不知道如何将新项目添加到列表中,因为当我尝试时,它会用新的项目覆盖现有项目。有人可以告诉我我做错了吗?

class Program
{
    static void Main(string[] args)
    {
        Master master = new Master();
        master.Username = "Barry";

        Quiz quiz = new Quiz();
        quiz.QuizID = "quiz ID";
        master.quiz = quiz;

        Answers answers = new Answers();
        answers.Answer1 = "answer 1";
        answers.Answer2 = "answer 2";
        answers.Answer3 = "answer 3";
        master.quiz.answers.Add(answers);
        answers.Answer1 = "answer 11";
        answers.Answer2 = "answer 22";
        answers.Answer3 = "answer 33";
        master.quiz.answers.Add(answers);
    }
}

public class Answers
{
    public string Answer1 { get; set; }
    public string Answer2 { get; set; }
    public string Answer3 { get; set; }
}

public class Quiz
{
    public string QuizID { get; set; }
    public List<Answers> answers = new List<Answers>();
}

public class Master
{
    public string Username { get; set; }
    public Quiz quiz { get; set; }
}

当我做第二次。添加,然后检查master.quiz.answers中的哪些内容显示两个条目,但它们同时是11,22,33值,就好像第二个。添加了列表中已有的数据。

感谢。

3 个答案:

答案 0 :(得分:3)

您需要使用new运算符构造两个不同的对象。

Answers answers = new Answers();
        answers.Answer1 = "answer 1";
        answers.Answer2 = "answer 2";
        answers.Answer3 = "answer 3";
        master.quiz.answers.Add(answers);

Answers anotherAnswer = new Answers(); // construct a new object here
        anotherAnswer.Answer1 = "answer 11";
        anotherAnswer.Answer2 = "answer 22";
        anotherAnswer.Answer3 = "answer 33";
        master.quiz.answers.Add(anotherAnswer);

顺便说一句,您可以使用对象初始化程序语法使其更清晰:

Answers answers = new Answers
{
      Answer1 = "answer 1",
      Answer2 = "answer 2",
      Answer3 = "answer 3"
};
master.quiz.answers.Add(answers);

Answers anotherAnswer = new Answers
{
      Answer1 = "answer 11",
      Answer2 = "answer 22",
      Answer3 = "answer 33"
}; 
master.quiz.answers.Add(anotherAnswer);

答案 1 :(得分:2)

尝试再次实例化答案对象,然后再将其添加到测验中。

answers = new Answers();

答案 2 :(得分:2)

因为您正在更新同一个对象。 使用

 answers = new Answers();
将对象添加到列表后