简体   繁体   中英

How to populate a List that's within a class in C#?

I'm trying to understand nested types, but even after checking several sites I still don't get it. I have a List that's in a class. I don't see how I can add new items to the List because when I try, it overwrites the existing items with my new ones. Can someone please tell me what I'm doing wrong?

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; }
}

When I do the second .Add and then check what's in master.quiz.answers it shows two entries, but they're both the 11, 22, 33 values as if the second .Add overwrote the data that was already in the list.

Thanks.

You'll need to construct two distinct objects with the new operator.

ie

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);

As an aside, you can make this a little bit cleaner with object initializer syntax:

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);

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

answers = new Answers();

Because you are updating the same object. use

 answers = new Answers();

after adding the object to the list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM