迭代器与中介者模式的深入解析
1. 迭代器相关内容
在编程中,迭代器是一个非常重要的概念。我们可以构建一个专门的 BinaryTree 类,将中序迭代器作为默认迭代器:
public class BinaryTree<T>
{
private Node<T> root;
public BinaryTree(Node<T> root)
{
this.root = root;
}
public InOrderIterator<T> GetEnumerator()
{
return new InOrderIterator<T>(root);
}
}
这里利用了鸭子类型(duck typing),即使不实现 IEnumerable 接口,也能使用 foreach 循环:
var root = new Node<int>(1,
new Node<int>(2), new Node<int>(3));
var tree = new BinaryTree<int>(root);
foreach (var node in tree)
WriteLine(node.Value); // 2 1 3
超级会员免费看
订阅专栏 解锁全文
1396

被折叠的 条评论
为什么被折叠?



