使用 .GetType() 可能会多次枚举 IEnumerable 警告
我收到 ReSharper 警告“可能存在多个 IEnumerable 枚举”,代码如下:
public void Mymethod(IEnumerable<int> entities)
{
var enumerator = entities.GetEnumerator();
var entityType = entities.GetType();
}
正如许多 stackoverflow-topics 中所描述的那样(以及 http://confluence.jetbrains.net/display/ReSharper/Possible+multiple+enumeration+of+IEnumerable) ReSharper 识别出查询运行了两次。
我的问题是,为什么“GetType()”语句被识别为查询。
有什么建议吗?
提前致谢。
I get the ReSharper warning "Possible multiple enumeration of IEnumerable" with following code:
public void Mymethod(IEnumerable<int> entities)
{
var enumerator = entities.GetEnumerator();
var entityType = entities.GetType();
}
As in much stackoverflow-topics described (and also on http://confluence.jetbrains.net/display/ReSharper/Possible+multiple+enumeration+of+IEnumerable) ReSharper recognizes that the query runs twice.
My question is, why the "GetType()" statement is recognized as a query.
Any suggestion?
thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只是 Resharper 不够聪明。
GetType
不是虚拟方法,它不会影响IEnumerable
。It's just Resharper not being smart enough.
GetType
isn't a virtual method, it can't affect theIEnumerable
.为了调用
GetTypes
,需要从 ReSharper 的角度评估entities
(它不知道GetTypes
是否需要要评估的枚举,这就是为什么它说“可能多个枚举”)。由于 ReSharper 发现方法中的多个位置具有相同的场景,因此它会发出此警告。这可能是问题,也可能不是问题,具体取决于实体代表什么以及您对其执行什么操作。如果它表示内存中的数组,或者您执行的操作不迭代列表,则无需担心。如果您迭代它,并且它表示将转到数据库的查询,那么最好显式枚举它(通过调用
ToList
或ToArray
)并对其执行操作相反的结果。In order for
GetTypes
to be invoked,entities
will need to be evaluated from ReSharper's point of view (it doesn't know whetherGetTypes
will require the enumeration to be evaluated, that's why it says "possible multiple enumeration"). Since ReSharper sees that there are several locations within the method where you have the same scenario, it issues this warning.This may or may not be a problem, depending on what
entities
represents and what operation you perform on it. If it represents an in-memory array, or you perform an operation that does not iterate over the list, it's not much to worry about. If you iterate over it, and it represents a query that will go to a database, it's probably good to enumerate it explicitly (by callingToList
orToArray
) and act on the result of that instead.