我只返回IEnumerable时可能多次枚举IEnumerable?

时间:2013-04-21 10:18:56

标签: c# resharper

ReSharper在此代码中说“可能多次枚举IEnumerable”:

public static IEnumerable<T> Each<T>(this IEnumerable<T> @this, Action<T> action)
{
    foreach (var i in @this)
        action(i);

    return @this;
}

但是我只是返回@this,我没有做任何其他事情...它是否警告我一旦函数返回可能会有额外的枚举,或者我在这里遗漏了什么?

2 个答案:

答案 0 :(得分:3)

  

但我只是回复@this,我没有做任何其他事情......

是的,但来电者可能也会列举它......

无论如何,使用像你在答案中所做的迭代器块更好,因为:

  • 避免多次枚举
  • 它维护延迟执行(即在您开始枚举Each的结果之前不会枚举源序列)

答案 1 :(得分:1)

这可以避免警告,我认为它更有效:

public static IEnumerable<T> Each<T>(this IEnumerable<T> @this, Action<T> action)
{
    foreach (var i in @this)
    {
        action(i);
        yield return i;
    }
}

有人可以验证它确实更有效(不会枚举两次吗?)?

相关问题