首页 文章

可能多次枚举IEnumerable - 如果我想要多个枚举怎么办?

提问于
浏览
1

我有一个创建文件结构的方法,并在多个视图模型实例中使用此文件结构 . 所以在这种情况下,假设一个问题或答案都有一个他们指向的“文件”列表的实例,每个问题/答案都可以修改它自己的实例 .

这是我的代码的简化版本 .

public void GeneratVms()
{
   List<IFile> files = _data.GetFiles();
   IEnumerable<IFileViewModel> fileVms = _generator.GenerateFileList(originalFileList);

   MyQuestionController = _generator.GenerateQuestionController(_questions, fileVms);
   MyAnswerController = _generator.GenerateAnswerController(_answers, fileVms);
}

然后问题/答案控制器生成器看起来像这样:

public IQuestionController GenerateQuestionController(
            List<IQuestion> questions, IEnumerable<IFileViewModel> files)
{
      IEnumerable<IQuestionViewModel> questionVms = 
                questions.Select(q => new QuestionViewModel(q, files));

      // Pass through these questions to the controller, and also the 
      // original file list, so the controller can create new instances 
      // of QuestionViewModel which will also have the file structure.
      return new QuestionController(questionVms, files); 
}

目前没有问题,它按预期工作 . 但是,ReSharper抱怨说“可能有多个IEnumerable枚举” . 这让我相信,也许我不是在明确我在做什么?

如果我将fileVms作为List处理,那么我传递给各种Questions / Answers的每个实例都被视为相同,因此如果你愿意,他们不能保留自己独特的“列表”版本 .

谁能提供更好的解决方案?

1 回答

  • 3

    出现此警告是因为 fileVmsIEnumerable<T> . 虽然运行时类型如果此实例可能是 List<T> ReSharper,则无法对此进行任何假设,从而返回消息 .

    但是,您可以通过将 fileVms 的类型更改为 List<T> 来避免这种情况 .

    作为你的方法 GenerateFileList 你也可以简单地忽略警告 . 但考虑这个实现:

    public IEnumerable<IFileViewModel> GenerateFileList(originalFileList) {
        return Enumerable.Range(0, 10).Select(new FileModel));
    }
    

    此方法确实返回迭代器而不是实际列表 . 因此,当您将其返回值提供给另一个方法两次时,您将迭代此迭代器两次 . 所以当你打电话

    IEnumerable<IQuestionViewModel> questionVms = 
        questions.Select(q => new QuestionViewModel(q, files));
    

    在你的 GenerateQuestionController 方法内和之后

    IEnumerable<IAnswerViewModel> answerVms = 
        answers.Select(a => new AnswerViewModel(a, files));
    

    GenerateAnswerController 中,你将迭代 files -参数两次,因此也会运行 GenerateFileList -method两次 .

相关问题