当我仅仅返回IEnumerable时,IEnumerable的可能的多个枚举

本文关键字:IEnumerable 枚举 返回 | 更新日期: 2023-09-27 18:10:07

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,我不做任何其他与它…它是警告我一旦函数返回可能会有额外的枚举,还是我在这里错过了一些东西?

当我仅仅返回IEnumerable时,IEnumerable的可能的多个枚举

但是我只是返回@this,我没有对它做任何其他事情…

是的,但是调用者可能也会枚举它…

无论如何,像你在回答中那样使用迭代器块会更好,因为:

  • 避免多重枚举
  • 它保持延迟执行(即源序列不会被枚举,直到你开始枚举Each的结果)

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

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

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