用于解释和QUOT ReSharper的的示例代码; IEnumerable的&QUOT的可能多枚举; [英] Resharper's example code for explaining "Possible multiple enumeration of IEnumerable"

查看:216
本文介绍了用于解释和QUOT ReSharper的的示例代码; IEnumerable的&QUOT的可能多枚举;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时ReSharper的警告一下:

Sometimes Resharper warns about:

的IEnumerable的可能多枚举

Possible multiple enumeration of IEnumerable

有的如何处理这个问题的 SO问题,ReSharper的网站也解释了事情这里。它有一些示例代码,告诉你这样做,而不是:

There's an SO question on how to handle this issue, and the ReSharper site also explains things here. It has some sample code that tells you to do this instead:

IEnumerable<string> names = GetNames().ToList();



我的问题是关于这个具体建议:不会这仍然导致通过集合枚举两次在2 - 每个循环?

My question is about this specific suggestion: won't this still result in enumerating through the collection twice in the 2 for-each loops?

推荐答案

GetNames()返回的IEnumerable 。所以,如果你存储的结果:

GetNames() returns an IEnumerable. So if you store that result:

IEnumerable foo = GetNames();



然后每次枚举时间中, GetNames()方法再次被调用(不是真的,我找不到一个链接,正确解释了细节,但看到的IEnumerable.GetEnumerator())。

Then every time you enumerate foo, the GetNames() method is called again (not literally, I can't find a link that properly explains the details, but see IEnumerable.GetEnumerator()).

Resharpes看到了这一点,并建议您存储的结果的枚举的 GetNames()在一个局部变量,例如通过在列表中物化吧:

Resharpes sees this, and suggests you store the result of enumerating GetNames() in a local variable, for example by materializing it in a list:

IEnumerable fooEnumerated = GetNames().ToList();

这将确保 GetNames()结果仅列举一次,只要你参考 fooEnumerated

This will make sure the GetNames() result is only enumerated once, as long as you refer to fooEnumerated.

这件事呢,因为你通常希望只有一次列举,例如,当 GetNames()执行(慢)数据库调用。

This does matter because you usually want to enumerate only once, for example when GetNames() performs a (slow) database call.

由于您的的列表中的结果,现在不说你列举事 fooEnumerated 两次;你会在内存中的列表两次迭代。

Because you materialized the results in a list, it doesn't matter anymore that you enumerate fooEnumerated twice; you'll be iterating over an in-memory list twice.

这篇关于用于解释和QUOT ReSharper的的示例代码; IEnumerable的&QUOT的可能多枚举;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆