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 .