简体   繁体   English

从父类型实例化一个孩子

[英]instantiating a child from a parent type

I have a base type which stores information about a question in a question pool for a system which generates practice question sets to help people study for multiple choice tests. 我有一个基本类型,该类型将有关问题的信息存储在系统的问题池中,该系统生成练习问题集以帮助人们学习多项选择题测试。 The only information that is stored in it are the answers, the prompt and question number. 存储在其中的唯一信息是答案,提示和问题编号。 When I create a practice test, I need to augment the type with some properties to store the answer submitted (the test can be taken in parts), and so I created the following classes: 创建练习测试时,我需要使用一些属性来扩展类型以存储提交的答案(测试可以分部分进行),因此我创建了以下类:

public class MultipleChoiceQuestion
{
    public Int32 Number { get; internal set; }
    public String Prompt { get; internal set; }
    public MultipleChoiceAnswer[] Choices { get; internal set; }

    // constructors, etc...
}

public class PracticeTestQuestion : MultipleChoiceQuestion
{
    public MultipleChoiceAnswer AnswerSelected { get; set; }

    // is this right?
    public PracticeTestQuestion(MultipleChoiceQuestion question)
    {
        ...
    }
}

Originally I had the MultipleChoiceQuestion as just a member of PracticeTestQuestion, but it added a lot of extra dots in my property accessors, and so I changed it to inherit the class as listed above. 最初,我只是作为PracticeTestQuestion的成员使用MultipleChoiceQuestion,但是它在属性访问器中添加了很多额外的点,因此我将其更改为继承上面列出的类。 Currently I am assigning all of the properties line for line in the constructor, and but it feels sort of cumbersome, and I was wondering if there is a better way. 目前,我正在为构造函数中的line分配所有属性line,但是感觉有点麻烦,我想知道是否有更好的方法。

The C# compiler doesn't like upsizing types for good reasons, so my question is what is the best way to go about instantiating my PracticeTestQuestions from their MultipleChoiceQuestion base types? C#编译器出于种种原因不喜欢升迁类型,因此我的问题是从他们的MultipleChoiceQuestion基本类型实例化PracticeTestQuestions的最佳方法是什么?

I would add a constructor to MultipleChoiceQuestion that takes another MultipleChoiceQuestion . 我会向MultipleChoiceQuestion添加一个构造函数,该构造函数采用另一个MultipleChoiceQuestion If necessary it can assign each of the properties in the constructor, but that's more appropriate, since it has the knowledge of its own properties. 如有必要,可以在构造函数中分配每个属性,但这更合适,因为它了解自己的属性。

Then in PracticeTestQuestion , you can just do: 然后,在PracticeTestQuestion ,您可以执行以下操作:

public PracticeTestQuestion(MultipleChoiceQuestion question) : base(question) { }

and be done with it. 并完成它。

My first gut reaction is to use a factory to create questions. 我的第一反应是使用工厂提出问题。 You ask the factory for a MCQ or a PTQ and it creates the right one. 您向工厂索要MCQ或PTQ,它将创建正确的MCQ或PTQ。

This is also more extensible to essay questions, true false, etc. 这也可以扩展到作文问题,对错等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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