I need to 2 levels of inheritance and abstraction in master-child relationship is the beginning of of the discussion.
What I want is to make sure all inherited objects from BaseMaster
must have a list of children, and the type of the children must inherit from BaseChild
. According to that post I have settled my design to
public abstract class BaseMaster<TChild> where TChild : BaseChild
{
public Collection<TChild> Children { get; }
}
public abstract BaseChild
{ }
public class FirstRealMaster : BaseMaster<FirstRealChild> { /* add more properties */ }
public class FirstChild : BaseChild { /* add more properties */ }
But with such design I lost the ability to use base object type to describe inherited objects, because BaseMaster<BaseChild> b = new FirstRealMaster();
won't be allowed, technically there are different types. Following is a sample code I hope I can make it work.
static BaseMaster<BaseChild> ReturnBaseMaster(int i)
{
if (i == 1)
{
return new FirstRealMaster();
}
else if (i == 2)
{
return new SecondRealMaster();
}
return null;
}
Such limitation caused lots of inconvenience. Any suggestion here how to improve the design to achieve my goal that I need object model to enforce all inherited classes to have children. And meanwhile I still want the flexibility to use base type for inherited types?