【发布时间】:2019-12-02 11:20:21
【问题描述】:
我有点困惑,为什么 不 Resharper(也不是 Studio 或 FX Cop:))在下面的代码中再次警告我可能对 IEnumerable 进行多次枚举:
//warning here fine
IEnumerable<IFileWrapper> filteredCollection = ctaWrappersContainer.FileContainer.Files.Where(x=>x.IsArchiveEntry);
int y1 = filteredCollection.Count();
int y2 = filteredCollection.Count();
//why no warning here?
int countOfIenumerable = ctaWrappersContainer.FileContainer.Files.Count();
int countOfIenumerableAgain = ctaWrappersContainer.FileContainer.Files.Count();
Files 集合是一个真正的 IEnumerable,每次调用都会重新计算。 以下是在代码中某处分配 Files 属性的方式:
container.Files = this.GetFilesFromArchive(container, zipFile.FullName, searchPattern);
GetFilesFromArchive() 正在枚举条目并一一返回(基于某些过滤器)。 因此,每次我调用计数时,它都会再次执行此操作(如预期的那样)
protected override IEnumerable<IFileWrapper> GetFilesFromArchive(FileContainer fileContainer, string zipFilePath, string searchPattern)
{
//do some filtering magic on a collection of entries in a zip
yield return new ZipEntryWrapper(fileContainer, zipEntry, zipFile);
}
【问题讨论】:
-
也许它不知道
FileContainer.Files每次访问时都返回相同的IEnumerable<T>。它有可能在其吸气剂中创建一个新的IEnumerable<T>。盲目添加此警告可能会产生大量误报。 -
你能发布代码而不是图像吗?由于防火墙限制,许多人(包括我自己)无法查看外部图像。
-
@MatthewWatson - 抱歉,没有意识到这一点!
-
另外,图片不能很好地用谷歌搜索。我们非常喜欢这里的代码和错误消息作为文本。
-
它不会警告您,原因与您拨打
Directory.EnumerateFiles()两次时它不会警告您的原因相同——因为据它所知,这会给您两个单独的可枚举项。所以我同意 /u/canton7 的想法。
标签: c# resharper ienumerable