如何从 IEnumerable 方法调用 IEnumerable 方法?
How to call an IEnumerable method from an IEnumerable method?
我有一个类似于下面的代码,但更复杂:
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());
}
我有一个类似于下面的代码,但更复杂:
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());
}