Skip to main content
 首页 » 编程设计

c#之通过无限循环生成元素返回 IEnumerableT> 是否有缺点

2024年02月05日12zhwl

这里的死循环有没有造成什么负面影响? 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 函数 - 主要是 All 和 Count - 永远不会完成。只要消费者有办法在某个时候打破循环,使用延迟执行的 Linq 查询就没问题。客户端必须确保使用确定性函数,例如 Take 或 First(假设在某个时候返回值会满足条件)。

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