Nested class with generics

The project I'm working on now requires me to create a tree data structure. Below is an example of how I tried to achieve this functionality. I decided to create a child node collection as a nested class, because it allows me to set the Nodes parent node to it using the Add () method, while preserving the parent setter private, so classes derived from node or other classes in the same assembly do not can get direct access to it.

class Node<T> where T : Node<T>
{
  private T mParent;
  private ChildNodeCollection<T> mChildren;

  public T Parent
  {
    get{return this.InnerParent;}
  }

  private T InnerParent
  {
     get{return this.mParent;}
     set {this.mParent = value;}
  }

  public Node()
  {
      this.mChildren = new ChildNodeCollection<T>(this);
  }

  class ChildNodeCollection<U> where U : T
  {
       private U mParent;

       public U CollectionParent
       {
           get{return this.mParent;}
       }

       public ChildNodeCollection(U parent)
       {
           this.mParent = parent;
       }


        public void Add(U item)
        {
            item.InnerParent = this.CollectionParent;

            ...
        }

  }
}

This code does not compile. It complains about a string this.mChildren = new ChildNodeCollection(this)in the node constructor. He throws these two errors.

Error   35  The best overloaded method match for Node<T>.ChildNodeColllection<T>.ChildNodeColllection(T)' has some invalid arguments

Error   36  Argument '1': cannot convert from Node<T> to T

, , T Node, . , - , - , node , node .

+3
3

, - :

this.mChildren = new ChildNodeCollection<T>(this);

, this Node<T>, T ( , ). , - Node<T> .

:

public Node() {
  this.mChildren = new ChildNodeCollection(this);
}

class ChildNodeCollection {
  private Node<T> mParent;

  public ChildNodeCollection(Node<T> parent) {
    this.mParent = parent;
  }
}

, ( T : Node<T>) . ( ), T (.. node). , , , generics.NET.

, Node<T> , node, T .

+3

, , U T.

this.mChildren = new ChildNodeCollection(this) U (Node<T>). T .

0

, protected

class Node<T> 
{
    protected Node<T> _parent;
    protected List<Node<T>> _children;

    protected T _value;

    protected Node() { }

    public Node(T value)
    {
        _parent = null;
        _value = value;
        _children = new List<Node<T>>();
    }

    public void AddChild(Node<T> child) 
    {            
        child._parent = this;
        _children.Add(child);
    }
}

class NaughtyNode : Node<int>
{
    //Naughty nodes dont have parents, only kids

    public NaughtyNode(int value)
    {
        _value = value;
        _children = new List<Node<T>>();
    }

    public void BeNaughty()
    {
        Node<int> victim = new Node<int>(1);
        victim._parent = this; //Does not work, cannot access
    }

    public void AddChild(NaughtyNode child)
    {
        _children.Add(child);
    }
}

protected Node<T>. NaughtyNode a Node<T> _parent.

0
source

All Articles