我有一个类:
class Spline
int ChildrenCount;
Spline GetChild (int index)
class SplineCollection : IEnumerable<Spline>
Spline Master
是否可以为 SplineCollection 编写一个递归的 IEnumerable,它将一个接一个地返回所有子项?
编辑:所以 Master 是根 Box,其子级的层次结构可以是任意深度。
编辑:通过使用名称 Box,我想我混淆了一些人。它应该是一个几何对象,而不是容器。所以将其更改为 Spline。
最佳答案
我会手动维护一个堆栈,而不是依赖于此处的调用堆栈。原因是因为一个新的 IEnumerable<Spline>
必须为每个 Spline
创建如果您通过递归调用获取后代的方法来使用调用堆栈,则已访问。那将是低效的。您可以使用自己的堆栈显着改进遍历。
public IEnumerable<Spline> Descendants
{
get
{
// This performs a simple iterative preorder traversal.
var stack = new Stack<Spline>(new Spline[] { this });
while (stack.Count > 0)
{
Spline current = stack.Pop();
yield return current;
for (int i = current.ChildrenCount - 1; i >= 0; i--)
{
stack.Push(current.GetChild(i));
}
}
}
}
关于c# - 是否可以编写一个递归的 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3631283/