C#新手求助:如何将类中答案元素存入List实现复用?
解决Quiz Maker中答案存入List的问题
问题说明
作为C#新手开发Quiz Maker,需要将类中的正确答案、错误答案存入List,实现批量处理用户输入,同时通过列表大小限制答案存储上限,现有代码中错误答案是单个属性,无法满足需求。
修改方案
1. 重构QuestionAndAnswers类
将单个错误答案属性替换为List,同时设置存储上限常量:
using System; using System.Collections.Generic; namespace Quiz_Maker { public class QuestionAndAnswers { public string UserQuestion { get; set; } public string CorrectAnswer { get; set; } // 存储所有错误答案的列表,初始化空列表 public List<string> IncorrectAnswers { get; set; } = new List<string>(); // 定义错误答案的最大存储数量,控制上限 public const int MaxIncorrectAnswers = 3; } }
2. 修改用户输入方法,批量处理答案输入
用循环批量获取错误答案,避免重复编写单个输入逻辑:
using System; namespace Quiz_Maker { public static class UserInterface { public static QuestionAndAnswers GetQuestionAndAnswers() { var userQnA = new QuestionAndAnswers(); Console.WriteLine("请输入你的问题: "); userQnA.UserQuestion = Console.ReadLine(); Console.WriteLine("请输入正确答案: "); userQnA.CorrectAnswer = Console.ReadLine(); // 循环获取错误答案,直到达到设定的上限 for (int i = 0; i < QuestionAndAnswers.MaxIncorrectAnswers; i++) { Console.WriteLine($"请输入第{i+1}个错误答案: "); string input = Console.ReadLine(); // 可选:过滤空输入,避免存入无效内容 if (!string.IsNullOrWhiteSpace(input)) { userQnA.IncorrectAnswers.Add(input); } } return userQnA; } } }
扩展功能(可选)
如果需要将正确答案和错误答案合并为一个可打乱的选项列表,可以在类中添加只读属性:
public List<string> AllOptions { get { var options = new List<string>(IncorrectAnswers); options.Add(CorrectAnswer); // 打乱选项顺序,模拟真实答题场景 Random rng = new Random(); return options.OrderBy(_ => rng.Next()).ToList(); } }
内容的提问来源于stack exchange,提问作者Casey Dent
相关产品推荐
相关产品推荐

