c# - 通过无限循环生成元素返回 IEnumerable<T> 是否有缺点?

标签 c# ienumerable infinite-loop

这里的无限循环是否会造成任何负面影响? Resharper 警告我...

Function never returns

..但我看不出这里有任何缺点。

public static class RandomEntityFactory
{
    public static IEnumerable<T> Enumerate<T>() where T : class
    {
        while (true)
        {
            yield return Get<T>();
        }
    }

    public static T Get<T>() where T : class
    {
        if (typeof(T) == typeof(Client)) return CreateRandomClient() as T;
        if (typeof(T) == typeof(Font)) return CreateRandomFont() as T;

        throw new Exception("unknown type: " + typeof(T).Name);
    }
}

最佳答案

Is there a downside?

这取决于预期用途。正如所写,某些 Linq 函数(主要是 AllCount)永远不会完成。只要消费者有办法在某个时刻中断循环,使用延迟执行的 Linq 查询就可以了。客户端必须确保使用确定性函数,例如 TakeFirst(假设在某个时刻返回值将满足条件)。

如果预期用途是让客户端使用 foreach 进行枚举,自行判断是否中断循环,那么无限期地返回项目是合理的。

关于c# - 通过无限循环生成元素返回 IEnumerable<T> 是否有缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34075125/

相关文章:

c# - 如何使用 C# 的 OrientDB-NET.binary 驱动程序在 OrientDB 上创建数据库?

c# - 使用 IEnumerable 检测修改

infinite-loop - 迭代无符号类型的每个值时如何避免无限循环?

linux - 如何在 Linux 后台无限运行脚本?

javascript - 在主干模型更改事件内具有更新属性的无限循环

c# - 语法:yield return enumerable without loop

c# - 创建 Entity Framework 模型时忽略数据库默认值

c# - Apple TV 的 TcpClient 或 HttpWebRequest 在 30 秒后结束?

asp.net-mvc - EditorFor ListView 错误

c# - 扩展 IEnumerable 的选择以在选择器中包含源