I'm designing a generic tree data structure in C# and I was wondering if I over designed it by having all those interfaces/classes:
public interface ITreeNode
{
object GenericValue { get; }
IEnumerable<ITreeNode> Children {get;}
}
public interface ITreeNode<T>:ITreeNode
{
T Value { get; }
}
public class TreeNode : ITreeNode
{
protected readonly LinkedList<ITreeNode> 开发者_如何学C_children = new LinkedList<ITreeNode>();
protected object _value;
public object GenericValue
{
get { return _value; }
}
public IEnumerable<ITreeNode> Children
{
get { return _children; }
}
}
public class TreeNode<T> : TreeNode, ITreeNode<T>
{
public T Value
{
get { return (T)base._value; }
}
}
- Could you please advice on improvements/simplifications?
- How would you implement a binary tree node? Use another 2 interfaces and another 2 classes or is there a better way?
What is needed for: we need to store some trees that are connected to other trees. So, a leaf in one tree can be a root in another. That's why all those generics and non-generics
First of all, do you even need TreeNode
? Why not use TreeNode<object>
instead and then make TreeNode<T>
type-safe without any casts whatsoever?
I think the interfaces here are fine.
i would remove the TreeNode < T > class and relative interface: you could implement a template method quite easily casting a generic object. This would avoid one interace and one derivation whitout sacrifying readability.
The interface is good, since a class can't derive from TreeNode.
A note: binary tree are a specialization of N-ary trees.
精彩评论