开发者

Is this too much inheritance/implementation?

开发者 https://www.devze.com 2023-03-02 13:44 出处:网络
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:

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; }
    }
}
  1. Could you please advice on improvements/simplifications?
  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号