我如何在包含子类的超类列表上调用子类方法

时间:2016-11-07 19:52:40

标签: c# class methods subclass

我很难写出我的标题,所以让我现在试着详细说明。首先是我的相关代码:

class Question
    {
        static bool checkFile(XElement q)
        {
            foreach (XElement a in q.Descendants())
            {
                if (a.Name.LocalName == "file")
                {
                    return true;
                }
            }
            return false;
        }
        protected string questionText;
        protected List<File> files;
        protected Question question;
        public Question(XElement q)
        {
            questionText = q.Element("questiontext").Element("text").Value.ToString();
            string name = q.Attribute("type").Value.ToString();
            if (checkFile(q))
                files.Add(new File(q));
        }
    }
    class multichoice : Question
    {
        private List<string> answers;
        public multichoice(XElement q)
            : base(q)
        {
            foreach (XElement a in q.Elements())
            {
                if (a.Name.LocalName == "answer")
                    answers.Add(a.Element("text").Value.ToString());
            }
        }
        public void writeQuestion(HtmlTextWriter writer)
        {
            writer.RenderBeginTag("p");
            writer.Write("<strong>Multiple Choice: </strong>" + this.questionText);
            writer.RenderEndTag();
            writer.AddAttribute("type", "A");
            writer.RenderBeginTag("ol");
            foreach (string answer in answers)
            {
                writer.RenderBeginTag("li");
                writer.Write(answer);
                writer.RenderEndTag();
            }
            writer.RenderEndTag();
        }
    }
    class truefalse : Question
    {
        public truefalse(XElement q)
            : base(q)
        {

        }
        public void writeQuestion(HtmlTextWriter writer)
        {
            writer.RenderBeginTag("strong");
            writer.Write("True or False : ");
            writer.RenderEndTag();
            writer.Write(questionText);
        }
    }

所以我创建了多种类型的问题,都是&#34;问题&#34;的子类。问题包含适用于每种类型问题的所有数据,这些子类包含对它们唯一的方法,主要是&#34; writeQuestion&#34;。 现在我正在尝试用它做的事情是这样的:

static List<Question> collectQuestions(XDocument doc)
    {
        XDocument xdoc = doc;
        string elementName = null;
        List<Question> questions = null;
        foreach (XElement q in xdoc.Descendants("question"))
        {
            elementName = q.Attribute("type").Value.ToString();
            if (elementName != "category")
                continue;
            if (elementName == "truefalse")
                questions.Add(new truefalse(q)); //writeTrueFalse(writer, q);
            else if (elementName == "calculatedmulti")
                questions.Add(new calculatedmulti(q)); // writeCalculatedMulti(writer, q);
            else if (elementName == "calculatedsimple")
                questions.Add(new calculatedsimple(q)); // writeCalculatedSimple(writer, q);
            else if (elementName == "ddwtos")
                questions.Add(new Draganddrop(q)); //writeDragAndDrop(writer, q);
            else if (elementName == "description")
                questions.Add(new Description(q)); // writeDescription(writer, q);
            else if (elementName == "essay")
                questions.Add(new Essay(q)); // writeEssay(writer, q);
            else if (elementName == "gapselect")
                questions.Add(new Gapselect(q)); // writeGapSelect(writer, q);
            else if (elementName == "matching")
                questions.Add(new Matching(q)); // writeMatching(writer, q);
            else if (elementName == "multichoice")
                questions.Add(new multichoice(q)); // writeMultipleChoice(writer, q);
            else if (elementName == "multichoiceset")
                questions.Add(new Allornothing(q)); // writeAllOrNothing(writer, q);
            else if (elementName == "numerical")
                questions.Add(new Numerical(q)); // writeNumerical(writer, q);
            else if (elementName == "shortanswer")
                questions.Add(new shortanswer(q)); // writeShortAnswer(writer, q);
            else
                continue;
        }
        return questions;
    }
questions = collectQuestions(someDocument);
foreach (Question question in questions)
            {
                question.writeQuestion(writer);
            } 

有没有办法在每个项目上调用writeQuestion?现在它当然给出了一个错误,即Question不包含writeQuestion的定义,即使它的每个子类都有。请评论我是否应该添加更多内容以澄清,我的代码已经有点受损,因为我一再重复它。我很喜欢和这样的课程一起工作,所以我可能会遗漏一些关键概念,请指出你看到的任何东西,谢谢你。

2 个答案:

答案 0 :(得分:4)

创建基类abstract,向基类添加一个抽象WriteQuestion成员,然后在每个具体实现中添加override

答案 1 :(得分:1)

恕我直言,我会将你的代码分成更多的类,以便更好地分离关注点。

您的Question课程和专业(即派生课程)不应该知道他们如何存储,而且他们也不应该知道他们如何变成某些人格式就像HTML表示。

我会定义一个名为XmlQuestionConverter的类:

public class XmlQuestionConverter
{   
    public XmlQuestionConverter() 
    {
        TypeToConvertMap = new Dictionary<Type, Action<Question, XElement>>
        {
            { typeof(TrueFalseQuestion), new Action<Question, XElement>(ConvertTrueFalseFromXml) }
            // other mappings...
        };
    }
    private Dictionary<Type, Action<Question, HtmlTextWriter>> TypeToConvertMap
    {
        get;
    }

     // This dictionary maps element names to their type
     private Dictionary<string, Type> QuestionTypeMap { get; } = new Dictionary<string, Type>()
     {
          { "truefalse", typeof(TrueFalseQuestion) },
          { "multichoice", typeof(MultiChoiceQuestion) }
          // And so on
     };

     public IList<Question> ConvertFromXml(XDocument questionsDocument)
     {
        // This will get all question elements and it'll project them
        // into concrete Question instances upcasted to Question base
        // class
        List<Question> questions = questionsDocument
                     .Descendants("question")
                     .Select
                     (
                        element =>
                        {
                           Type questionType = QuestionTypeMap[q.Attribute("type").Value];
                           Question question = (Question)Activator.CreateInstance(questionType);

                           // Calls the appropiate delegate to perform specific
                           // actions against the instantiated question
                           TypeToConvertMap[questionType](question, element);

                           return question;
                        }
                     ).ToList();

        return questions;
     }

     private void ConvertTrueFalseFromXml(TrueFalseQuestion question, XElement element)
     {
          // Here you can populate specific attributes from the XElement
          // to the whole typed question instance!
     }
}

现在,您可以将XDocument转换为问题列表,我们已准备好将其转换为带有HtmlTextWriter的HTML:

public class HtmlQuestionConverter
{
    public HtmlQuestionConverter() 
    {
        TypeToConvertMap = new Dictionary<Type, Action<Question, HtmlTextWriter>>
        {
            { typeof(TrueFalseQuestion), new Action<Question, HtmlTextWriter>(ConvertTrueFalseToHtml) }
            // other mappings...
        };
    }

    private Dictionary<Type, Action<Question, HtmlTextWriter>> TypeToConvertMap
    {
        get;
    }

    public void ConvertToHtml(IEnumerable<Question> questions, HtmlTextWriter htmlWriter)
    {
        foreach (Question question in questions)
        {
            // Calls the appropiate method to turn the question
            // into HTML using found delegate!
            TypeToConvertMap[question.GetType()](question, htmlWriter);
        }
    }

    private void ConvertTrueFalseToHtml(Question question, HtmlTextWriter htmlWriter)
    {
        // Code to write the question to the HtmlTextWriter...
    }
}

走这条路,我根本不知道你需要多态性:

XmlQuestionConverter xmlQuestionConverter = new XmlQuestionConverter();
IList<Question> questions = xmlQuestionConverter.ConvertFromXml(xdoc);

HtmlQuestionConverter htmlQuestionConverter = new HtmlQuestionConverter();
htmlQuestionConverter.ConvertToHtml(questions, htmlWriter);

注意:我无法尝试执行此代码,并且我不能100%确定它是否有效,但它是了解如何实施的良好开端你的代码明确分开了关注点!您可能需要进行一些调整以使我的代码适应您的实际用例。