即使与QUOT; IsNullOrEmpty"检查给" IEnumerable的&QUOT的可能多枚举;警告 [英] Even "IsNullOrEmpty" checks give "Possible multiple enumeration of IEnumerable" warnings

查看:138
本文介绍了即使与QUOT; IsNullOrEmpty"检查给" IEnumerable的&QUOT的可能多枚举;警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有是关于可能的多个枚举关于SO一问题了,但这个问题更具体。

There's a question on SO about "possible multiple enumerations" already, but this question is more specific.

请考虑下面的方法,它需要一个的IEnumerable<串> 作为输入并执行针对它的每个元素的给定方法

Please consider the following method, which takes an IEnumerable<string> as input and executes a given method against each of its elements:

public static bool SomeMethod(IEnumerable<string> enumerable)
{
    if (enumerable.IsNullOrEmpty())
    {
        // throw exception.
    }
    else
    {
        return (enumerable.All(SomeBooleanMethod));
    }
}

在上面的代码中, IsNullOrEmpty 是运行在

In the code above, IsNullOrEmpty is just an extension method which runs

return (!ReferenceEquals(enumerable, null) || enumerable.Any());

的问题是,ReSharper的警告我有关的IEnumerable可能的多个枚举,我真不知道,如果这实际上是一个问题或没有。

The problem is that ReSharper is warning me about "Possible multiple enumerations of IEnumerable", and I really don't know if this can actually be a problem or not.

我了解警告的意思,但是你能真正做到在这种情况下,如果你真的需要检查和无效或emptyness的情况下抛出异常?

I understand the meaning of the warning, but what could you really do in this situation if you really need to check and throw exception in case of nullity or emptyness?

推荐答案

这意味着在你的(部分)迭代了IEnumerable不止一次:先在您的来电任何()(其需要至少初始化迭代以查看是否可枚举返回任何元素),并在第二时间全部(其从一开始迭代)。

It means that you are (partially) iterating over the IEnumerable more than once: first in your call to Any() (which needs to at least initialize an iteration to see if the enumerable returns any elements), and a second time in All (which iterates from the beginning).

ReSharper的原因,警告您这是列举了可枚举可能会引起副作用,并无意中迭代两次可能会引发副作用的两倍,其可以是或可以不是理想的。

The reason ReSharper warns you about this is that enumerating over an enumerable may cause side effects, and unintentionally iterating twice may trigger the side effects twice, which may or may not be desirable.

这篇关于即使与QUOT; IsNullOrEmpty&QUOT;检查给&QUOT; IEnumerable的&QUOT的可能多枚举;警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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