我目前正在尝试通过dotnetacademy学习C#。在期末考试中,我的最后一步是说明:
请修改入口点方法以声明Survey类型的实例。声明后,在您选择的调查中添加两个文本问题。
接下来,在两个问题声明之后,创建一个返回GetScore方法结果的新本地声明。
- 醇>
最后,打印消息"您的分数:{分数}"使用WriteLine到控制台,其中{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
答案 0 :(得分:0)
在你们的帮助下,它现在通过了:
public static void Main()
{
Survey survey = new Survey("Survey");
Question tq1 = new TextQuestion();
Question tq2 = new TextQuestion();
tq1.Ask();
tq2.Ask();
survey.AddQuestion(tq1);
survey.AddQuestion(tq2);
int score = survey.GetScore();
Console.WriteLine("Your score: {0}", score);
}
}