【发布时间】:2010-03-10 13:01:48
【问题描述】:
我正在编写一个不可变的二叉树类,其中所有方法(Insert、Remove、RotateLeft 等)都返回一个树的新实例,而不是就地修改它。
我将创建许多不同的树实现:Avl 树、红黑树、splay 树等。我有以下内容:
public class AbstractBinaryTree<TreeType, T>
where TreeType : AbstractBinaryTree<TreeType, T>
where T : IComparable<T>
{
protected abstract TreeType CreateNode(TreeType left, T value, TreeType right);
protected abstract T Value { get; }
protected abstract TreeType Left { get; }
protected abstract TreeType Right { get; }
protected abstract bool IsNil();
public TreeType Insert(T item)
{
if (this.IsNil())
{
return CreateNode(this, item, this);
// ^ doesn't compile, can't convert type
// AbstractBinaryTree<TreeType, T> to type TreeType
}
else
{
int compare = item.CompareTo(this.Value);
if (compare < 0)
{
return CreateNode(this.Left.Insert(item), this.Value, this.Right);
}
else if (compare > 0)
{
return CreateNode(this.Left, this.Value, this.Right.Insert(Value));
}
else
{
return this;
// ^ doesn't compile, can't converrt type
// AbstractBinaryTree<TreeType, T> to type TreeType
}
}
}
}
这里的想法是 AbstractBinaryTree 是一个树节点——不仅如此,它与TreeType 的类型相同。如果我能让上面的基类正常工作,那么我可以写这样的东西:
public class AvlTree<T> : AbstractBinaryTree<AvlTree<T>, T>
{
public override AvlTree<T> Insert(T item) { return Balance(base.Insert(item)); }
}
以便我的 Insert 方法返回 AvlTree<T> 而不是 AbstractBinaryTree<AvlTree<T>, T>。但是我什至无法做到这一点,因为基类无法编译。
如何将 AbstractBinaryTree 的实例传递给采用 TreeType 类型的方法?
【问题讨论】: