So I wish to setup an abstract base class to derive children classes from. All the work will take place on the children, but I wanted the children to be able to reference each other.
Here is some pseudo-code:
public abstract class BaseClass<T> : SomeOtherClass {
public List<BaseClass> listOfChildren;
protected T thisChild;
public void DoMoreStuff(){
Debug.Log("Doing more stuff");
}
protected virtual void DoSomething(int i){
listOfChildren[i].DoMoreStuff();
}
}
public class FirstChildClass : BaseClass<FirstChildClass> {
FirstChildClass<T>(){
thisChild = this;
}
public void FirstClassStuff(){
Debug.Log("first class stuff");
}
}
public class SecondChildClass : BaseClass<SecondChildClass> {
public void SecondClassStuff(){
Debug.Log("second class stuff");
}
}
How would I make a generic List to accept any child class?
Will I need to typecast listOfChildren with T to use DoMoreStuff()?
On its own, is there anything else inherently wrong with this setup?
I think you overcompicate the solution. If you don't want to store any data in each node - try to solve this problem then without the generics. I will give you a naive straight-forward implementation of desired behavior as a starting point.
public abstract class BaseClass {
private IList<BaseClass> children = new List<BaseClass>();
public void AddChild(BaseClass child)
{
this.children.Add(child);
}
protected virtual void DoMoreStuff(){
Debug.Write("Doing more stuff");
}
public void DoSomething(int i){
children[i].DoMoreStuff();
}
}
public class FirstChildClass : BaseClass {
protected override void DoMoreStuff(){
Debug.Write("first class more stuff");
}
}
public class SecondChildClass : BaseClass {
protected override void DoMoreStuff(){
Debug.Write("second class more stuff");
}
}
now you can
var root = new FirstChildClass();
root.AddChild(new FirstChildClass());
root.AddChild(new SecondChildClass());
root.AddChild(new FirstChildClass());
root.DoSomething(1); //will print second class more stuff
root.DoSomething(0); //will print first class more stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With