J
Jon Slaughter
I do not understand how to implement these two classes. I created a tree
like structure and I implemented the ability to enumerate over it but I'm
mixing generic and nongeneric classes:
This is the class that works:
public class RTree<T> : IEnumerable
{
public List<RTree<T>> Nodes; // Container for Nodes
public T Value; // Value at this node
public RTree<T> Parent; // Contains the parent node
public RTree() { Nodes = new List<RTree<T>>(); }
public void Add(RTree<T> node)
{
Nodes.Add(node);
node.Parent = this;
}
public virtual IEnumerator GetEnumerator()
{
return new TreeIterator(this);
}
public class TreeIterator : IEnumerator
{
private RTree<T> tree;
private int index = -1;
public TreeIterator(RTree<T> t)
{
tree = t;
}
public bool MoveNext()
{
index++;
if (index < tree.Nodes.Count)
return true;
return false;
}
public object Current
{
get
{
if (index <= -1)
throw new InvalidOperationException();
return tree.Nodes[index];
}
}
public void Reset() { index = -1; }
}
}
But if I do not add
using System.Collections; and keep System.Collections.Generic then I get
errors about Current returning object and if I change that then I get the
error about it not returning object.
Do I need to implement two subclasses, one for the generic version and one
for the non-generic?
If so, is there any benefit to using one over the other? Basically whats the
point of having both a non-generic IEnumerator and a generic one? Also, is
one prefered over the other?
Thanks,
Jon
like structure and I implemented the ability to enumerate over it but I'm
mixing generic and nongeneric classes:
This is the class that works:
public class RTree<T> : IEnumerable
{
public List<RTree<T>> Nodes; // Container for Nodes
public T Value; // Value at this node
public RTree<T> Parent; // Contains the parent node
public RTree() { Nodes = new List<RTree<T>>(); }
public void Add(RTree<T> node)
{
Nodes.Add(node);
node.Parent = this;
}
public virtual IEnumerator GetEnumerator()
{
return new TreeIterator(this);
}
public class TreeIterator : IEnumerator
{
private RTree<T> tree;
private int index = -1;
public TreeIterator(RTree<T> t)
{
tree = t;
}
public bool MoveNext()
{
index++;
if (index < tree.Nodes.Count)
return true;
return false;
}
public object Current
{
get
{
if (index <= -1)
throw new InvalidOperationException();
return tree.Nodes[index];
}
}
public void Reset() { index = -1; }
}
}
But if I do not add
using System.Collections; and keep System.Collections.Generic then I get
errors about Current returning object and if I change that then I get the
error about it not returning object.
Do I need to implement two subclasses, one for the generic version and one
for the non-generic?
If so, is there any benefit to using one over the other? Basically whats the
point of having both a non-generic IEnumerator and a generic one? Also, is
one prefered over the other?
Thanks,
Jon