【发布时间】:2020-01-18 09:50:08
【问题描述】:
我有一个类似于以下的代码,但更复杂:
IEnumerable<SomeObject> GetObjects()
{
if (m_SomeObjectCollection == null)
{
yield break;
}
foreach(SomeObject object in m_SomeObjectCollection)
{
yield return object;
}
GetOtherObjects();
}
IEnumerable<SomeObject> GetOtherObjects()
{
...
}
我刚刚意识到,GetOtherObjects() 方法不能从OtherObjects() 方法调用。 没有错误,但迭代停止。有什么办法解决吗?
【问题讨论】:
-
在
GetOtherObjects()上执行foreach就像您对m_SomeObjectCollection所做的那样。 -
如所写,您的方法首先不需要迭代器:
return m_SomeObjectCollection ?? GetOtherObjects() ?? Enumerable.Empty<SomeObject>()或其一些变体应该可以。 (不过,如果可以的话,首先尝试摆脱null—— 始终实例化集合,即使是空的,作为不变量也是有用的。)
标签: c# .net ienumerable