我有一个 IEnumerable,我需要从中获取每个项目并一个一个地显示它。显示不是一个连续的过程..即我应该获取一个项目并将其显示在 UI 上,然后等待一些用户对该项目的反馈,然后转到下一个项目。例如,从下面的代码中,我需要获取一个问题,然后将其显示给用户,然后用户按 Enter,然后我继续获取下一个问题。
我的问题是我该怎么做?IEnumerable 是实现这一目标的最佳方式,还是我应该恢复列出并开始存储索引并一一递增?
请注意,我使用的是 .NET 3.5。
代码:
class Program
{
static void Main(string[] args)
{
Exam exam1 = new Exam()
{
Questions = new List<Question>
{
new Question("question1"),
new Question("question2"),
new Question("question3")
}
};
var wizardStepService = new WizardStepService(exam1);
var question = wizardStepService.GetNextQuestion();
//Should output question1
Console.WriteLine(question.Content);
Console.ReadLine();
//Should output question2 but outputs question1
question = wizardStepService.GetNextQuestion();
Console.WriteLine(question.Content);
Console.ReadLine();
//Should output question3 but outputs question1
question = wizardStepService.GetNextQuestion();
Console.WriteLine(question.Content);
Console.ReadLine();
}
}
public class Question
{
private readonly string _text;
public Question(string text)
{
_text = text;
}
public string Content { get { return _text; } }
}
internal class Exam
{
public IEnumerable<Question> Questions { get; set; }
}
internal class WizardStepService
{
private readonly Exam _exam;
public WizardStepService(Exam exam)
{
_exam = exam;
}
public Question GetNextQuestion()
{
foreach (var question in _exam.Questions)
{
//This always returns the first item.How do I navigate to next
//item when GetNextQuestion is called the second time?
return question;
}
//should have a return type hence this or else not required.
return null;
}
}