gpt4 book ai didi

asp.net-mvc-4 - MVC4 模型属性应该是另一个类的列表或 ICollection

转载 作者:行者123 更新时间:2023-12-02 03:45:37 24 4
gpt4 key购买 nike

我正在使用 Entity Framework 代码优先制作一种测试生成应用程序。我有一个名为 Question 的基类,MultipleChoiceQuestionEssayQuestion 和其他问题类型都来自该基类。 MultipleChoiceQuestions 显然有多个答案,考生必须从中选择。我的问题与选择将它们存储在问题实例中的最佳方式有关。

我可以用一个字符串列表来声明这个类来保存答案,就像这样:

public class MulitpleChoiceQuestion : Question
{
private List<String> Answers = new List<String>();
// other declarations, etc.
}

相反,我可以声明另一个名为 Answers 的类,并让我的 Question 类使用 Answers 的集合。

public class Answer
{
public int AnswerID { get; set; }
public String AnswerText { get; set; }

public virtual Question Question { get; set; }
}

然后在我的问题子类中(不仅仅是MultipleChoiceQuestions)

public class MulitpleChoiceQuestion : Question
{
public virtual ICollection<Answer> Answers { get; set; }
// other declarations, etc.
}

有没有比这两种方法更好的方法?如果不是,哪一个更好,为什么?我很难在网上找到如此详细的内容,而且大多数书籍也没有深入到这里。在此先感谢您的指导。

最佳答案

我问过我的一位 .NET 教授 friend 这个问题,这是他的回答:

Both of your declarations are invoking collections. A list is a typed collection while ICollection is untyped. Typed Collection (List) has two advantages over untyped collections. The type of each collection is checked at compile time and thus preventing runtime errors. Second, they reduce the amount of casting that is needed when retrieving objects.

我首先实现了 ICollection 解决方案,它在几个地方很笨拙(例如,种子数据的初始化程序):

    var mcQuestions = new List<MultipleChoiceQuestion>
{
new MultipleChoiceQuestion {
QuestionText = "What is the value returned by the expression (true == false? 'yes': 'no')?",
Answers = new List<Answer> { new Answer { AnswerText="true"}, new Answer { AnswerText = "false"}, new Answer { AnswerText = "can't be determined"}, new Answer {AnswerText = "45"}, new Answer { AnswerText = "blue"}}
},
new MultipleChoiceQuestion {
QuestionText = "C-Sharp responds to a global variable declaration by:",
Answers = new List<Answer> { new Answer { AnswerText="throwing a compile error"}, new Answer { AnswerText = "throwing a runtime error"}, new Answer { AnswerText = "Throwing an Invalid operator warning"}, new Answer {AnswerText = "Printing a warning to the console"}, new Answer { AnswerText = "doing nothing; global variables are legal"}}
}
};
mcQuestions.ForEach(mcq => context.MultipleChoiceQuestions.Add(mcq));
context.SaveChanges();

虽然这个解决方案可能更灵活,但我认为从长远来看,List 会更简洁,更易于维护。我想不出保持复杂性作为 future 可能的灵 active 权衡的理由。所以这是我的 list 。希望这可以帮助其他人。祝你好运,好的代码。J

关于asp.net-mvc-4 - MVC4 模型属性应该是另一个类的列表或 ICollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17392477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com