首页 > 解决方案 > 不知道使用哪种类型的数组 C#

问题描述

我需要创建一个包含 10 个问题和每个问题 3 个答案的小测验。所以我有一个带有问题的数组和一个带有正确答案的数组。但我不知道要为所有答案使用哪个数组(正确的和不正确的)。注意:我会打乱每个数组以随机化所有内容。

标签: c#arrays

解决方案


没有开箱即用的数组类型可以满足您的要求。您可以创建一些存储和处理测验数据的类型。例子:

public class Answer
{
    public bool IsTrue { get; set; } = false;
    public string Text { get; set; } = string.Empty;
}

public class Question
{
    public string Text { get; set; } = string.Empty;
    public List<Answer> Answers { get; set; } = new List<Answer>();
}

public class Quiz
{
    public List<Question> Questions { get; set; } = new List<Question>();
}

var question1 = new Question()
{
    Text = "When should I use an array instead of List<T>?",
    Answers = new List<Answer>
    {
        new Answer() {IsTrue = true, Text = "If you don't know what a generic is."},
        new Answer() {IsTrue = false, Text = "If you want to save tons of memory."},
        new Answer() {IsTrue = false, Text = "If you want faster code."},
    }
};

var quiz = new Quiz();
quiz.Questions.Add(question1);

推荐阅读