【发布时间】:2018-08-17 03:18:17
【问题描述】:
因此,在长期中断网络管理员之后重新开始编码......并在我前进的过程中学习 C#(和 Unity)。试图绕过IEnumerable & IEnumerator
现在,这是我用来测试/弄清楚它的类的示例代码......它可以工作,递归地创建树/叶节点但是我一直在检索它们
public class NodeTest : IEnumerable
{
public int Counter;
public List<NodeTest> children;
public NodeTest(int count)
{
Counter = count;
Debug.Log("Creating " + count);
NodeTest tmpNode;
if(count>1)
{
children = new List<NodeTest>();
tmpNode = new NodeTest(Counter - 1);
children.Add(tmpNode);
tmpNode = new NodeTest(Counter - 1);
children.Add(tmpNode);
}
}
public IEnumerator GetEnumerator()
{
foreach(NodeTest n in this.children)
{
yield return n;
}
}
}
然后在我使用的其他地方:
foreach(NodeTest nt in tstNode)
{
Debug.Log(nt.Counter);
}
哪个检索顶部节点的孩子很好,但不会遍历孩子来获取他们的孩子等。我猜我必须在 IEnumerator GetEnumerator 方法中做更多事情?
【问题讨论】:
-
如果您的所有项目都来自 NodeTest 类型,您为什么选择使用更具体且更易于使用的接口 IEnumerable IEnumerable
,这也可以让您轻松使用 LINQ 处理结果。
标签: c# ienumerable ienumerator