【发布时间】:2017-09-08 22:18:25
【问题描述】:
我目前正在尝试通过 dotnetacademy 学习 C#。在期末考试中,我处于最后一步,说明如下:
请修改入口点方法以声明调查类型的实例。在声明之后,在您选择的调查中添加两个文本问题。
接下来,在两个问题声明之后,创建一个返回 GetScore 方法结果的新本地声明。
最后,使用 WriteLine 将消息“您的分数:{Score}”打印到控制台,其中 {Score} 是从调查中获得的分数。
我已经完成了我认为的最后两个步骤,因为我可以打印乐谱。我需要第 1 步的帮助。
这是我的代码:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string [] args)
{
Survey survey = new Survey("Survey");
survey.Questions.AsReadOnly();
TextQuestion tq = new TextQuestion();
survey.AddQuestion((Question)tq.Ask());
int score = survey.GetScore();
Console.Write("Your score: {0}", score);
}
}
public abstract class Answer
{
public int Score { get; set; }
}
public abstract class Question
{
public string Label { get; set; }
protected abstract Answer CreateAnswer(string input);
protected virtual void PrintQuestion()
{
Console.WriteLine(Label);
}
public Answer Ask()
{
PrintQuestion();
string input = Console.ReadLine();
return CreateAnswer(input);
}
}
public class TextAnswer : Answer
{
public string Text { get; set; }
}
public class TextQuestion : Question
{
protected override Answer CreateAnswer(string input)
{
return new TextAnswer { Text = input, Score = input.Length };
}
}
public class Survey
{
public Survey(string title)
{
Title = title;
Questions = new List<Question>();
}
public string Title { get; set; }
public List<Question> Questions { get; private set; }
public void AddQuestion(Question question)
{
Questions.Add(question);
}
public int GetScore()
{
int total = 0;
foreach (Question question in Questions)
{
Answer answer = question.Ask();
total = total + answer.Score;
}
return total;
}
我无法将问题添加到调查实例,因为它需要问题类型的问题参数。有什么建议吗?
最后,这是练习的链接:Exercise
【问题讨论】:
-
试试
survey.AddQuestion(tq)? -
在survey.AddQuestion(tq) 之前放tq.Ask();
-
该课程中的教程确实解释了要完成问题要做什么,并且看看到目前为止您已经完成了哪些工作,您似乎需要做更多的学习。请不要使用 SO 来帮助考试,因为它会减损您的学习体验。
-
是的,我已经尝试过了,我没有收到编译错误,但这不只是 TextQuestion 的一个实例吗?我应该添加两个文本问题,但也许我觉得很奇怪,但我想传递一个字符串,尽管它只需要一个 Questions 作为参数。
标签: c# .net list generic-list