I need to 2 levels of inheritance and abstraction in master-child relationship

后端 未结 2 561
Happy的楠姐
Happy的楠姐 2021-01-24 12:56

Let\'s assume I have a business case I want to use some model to represent a master-child structure. And there will be certain classes to inherit from both the master class and

相关标签:
2条回答
  • 2021-01-24 13:10

    Generics + potentially non-generic base class for your "with children" type is the standard solution. If you don't need BaseMaster to be assignment-compatible between different types of child nodes you can remove base non-generic class.

    Something roughly like following:

    public class BaseMaster
    {
        public ReadOnlyCollection<BaseChild> Children { get; }
    }
    
    public class BaseMaster<T> : BaseMaster where T: BaseChild
    {
        public new IEnumerable<T> Children { get
            {
               return base.Children.Cast<T>();
            };
        }
    }
    
    0 讨论(0)
  • 2021-01-24 13:16

    You may get somewhere with generics:

    public abstract class BaseMaster<TChild> where TCHild : BaseChild
    {
        // this probably doesn't have to be 'abstract' anymore
        public abstract ReadOnlyCollection<TChild> Children { get; }
    }
    
    public class FirstRealMaster : BaseMaster<FirstRealChild>
    {
    }
    

    But we don't know enough about the relation between Master and Child classes to be sure.

    0 讨论(0)
提交回复
热议问题