这是太多的继承/实现吗?
我正在用 C# 设计一个通用树数据结构,我想知道我是否通过拥有所有这些接口/类来过度设计它:
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> _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; }
}
}
- 您能否提供有关改进/简化的建议?
- 您将如何实现二叉树节点?使用另外2个接口和另外2个类还是有更好的方法?
需要什么:我们需要存储一些与其他树相连的树。因此,一棵树上的叶子可以是另一棵树上的根。这就是为什么所有这些泛型和非泛型
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> _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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您是否需要 TreeNode?为什么不使用
TreeNode
我认为这里的接口很好。
First of all, do you even need
TreeNode
? Why not useTreeNode<object>
instead and then makeTreeNode<T>
type-safe without any casts whatsoever?I think the interfaces here are fine.
我会删除TreeNode T > 类和相关接口:您可以非常轻松地实现模板方法来转换通用对象。这将避免一种交互和一种派生而不牺牲可读性。
该接口很好,因为类不能从TreeNode派生。
注意:二叉树是 N 叉树的特化。
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.