我有一个类似于下面的代码,但更复杂:
IEnumerable<SomeObject> GetObjects()
{
if (m_SomeObjectCollection == null)
{
yield break;
}
foreach(SomeObject object in m_SomeObjectCollection)
{
yield return object;
}
GetOtherObjects();
}
IEnumerable<SomeObject> GetOtherObjects()
{
...
}
我刚刚意识到,GetOtherObjects()
方法不能从 OtherObjects()
方法调用。 没有错误,但迭代停止。有什么办法可以解决吗?
最佳答案
添加foreach
和yield return
:
IEnumerable<SomeObject> GetObjects()
{
if (m_SomeObjectCollection == null)
{
yield break;
}
foreach(SomeObject item in m_SomeObjectCollection)
{
yield return item;
}
foreach (var item in GetOtherObjects())
yield return item;
}
另一种可能性是 Linq Concat
:
Enumerable<SomeObject> GetObjects()
{
return m_SomeObjectCollection == null
? new SomeObject[0] // yield break emulation: we return an empty collection
: m_SomeObjectCollection.Concat(GetOtherObjects());
}
关于c# - 如何从 IEnumerable 方法调用 IEnumerable 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57975804/