使用 .GetType() 可能会多次枚举 IEnumerable 警告

发布于 2024-12-27 18:20:43 字数 568 浏览 1 评论 0原文

我收到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

涫野音 2025-01-03 18:20:43

只是 Resharper 不够聪明。 GetType 不是虚拟方法,它不会影响 IEnumerable

It's just Resharper not being smart enough. GetType isn't a virtual method, it can't affect the IEnumerable.

老街孤人 2025-01-03 18:20:43

为了调用 GetTypes,需要从 ReSharper 的角度评估 entities(它不知道 GetTypes 是否需要要评估的枚举,这就是为什么它说“可能多个枚举”)。由于 ReSharper 发现方法中的多个位置具有相同的场景,因此它会发出此警告。

这可能是问题,也可能不是问题,具体取决于实体代表什么以及您对其执行什么操作。如果它表示内存中的数组,或者您执行的操作不迭代列表,则无需担心。如果您迭代它,并且它表示将转到数据库的查询,那么最好显式枚举它(通过调用 ToListToArray)并对其执行操作相反的结果。

In order for GetTypes to be invoked, entities will need to be evaluated from ReSharper's point of view (it doesn't know whether GetTypes 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 calling ToList or ToArray) and act on the result of that instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文