I have an abstract BaseItem class declared as follows:
public abstract class BaseItem { public BaseItem Parent { get; protected set; } public List<BaseItem> Children = new List<BaseItem>(); public abstract string Function1(); }
Basically, I am trying to implement a project in which each element has a parent element that will have one particular type and child elements that will have a different type.
For example, ItemA will have children for all ItemB types. Then ItemB will have the parent type ItemA and all types of ItemC. ItemC will have a parent ItemB and child items of type ItemD.
I thought it would be tidier to use this with generics to avoid unnecessary throws, as I know what type the parent and child will be for each of my inherited classes. So I came up with something like this:
public abstract class AbstractBase { public abstract string Function1(); } public abstract class BaseItem<T1, T2> : AbstractBase where T1 : AbstractBase where T2 : AbstractBase { public T1 Parent { get; protected set; } public List<T2> Children = new List<T2>(); } public class ItemA : BaseItem<ItemA, ItemB> { } public class ItemB : BaseItem<ItemA, ItemC> { } public class ItemC : BaseItem<ItemB, ItemD> { } public class ItemD : BaseItem<ItemC, ItemD> { }
So, two things. 1. Is it a good design? Is there an easier / better way to do this? I don't like using a second abstract base class to use generics. 2. If I hold it, what's the best way to handle the ends? (for example, ItemA does not have a parent in my actual problem domain, but you need a parent to compile it. ItemD does not have children, but I need to give something)
generics c #
David A.
source share