这里的无限循环是否会造成任何负面影响? 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
进行枚举,自行判断是否中断循环,那么无限期地返回项目是合理的。
关于c# - 通过无限循环生成元素返回 IEnumerable<T> 是否有缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34075125/