Class with generic list of the inherited class typ

2019-09-16 11:39发布

问题:

I have 3 class:

some of theme have list called descendents of some type.

I would like to have a generic class in the BaseHeaderFooterItem class. and insery and type of list to it.

Is there any option ?

#region ParentItem
public class BaseHeaderFooterItem
{
    public string Title { get; set; }
    public string EnTitle { get; set; }
    public HyperLink Link { get; set; }
    public int Level { get; set; }
}
#endregion

#region HeaderFooter
public class HeaderFooter : BaseHeaderFooterItem
{
    public List<Category> Descendants { get; set; }
}
#endregion

#region HeaderFooter
public class Category : BaseHeaderFooterItem
{
    public List<Show> Descendants { get; set; }
}
#endregion

#region Header
public class Show : HeaderFooter
{
    public string ImagePath { get; set; }
    public string MobileLink { get; set; }
    public string MobileLinkTarget { get; set; }
}
#endregion

#region TvGuid
public class TvGuid : Show
{
    public string Date { get; set; }
    public string Time { get; set; }
    public int IsActive { get; set; }
    public int NoProgram { get; set; }
}
#endregion

回答1:

If you want to use generics, you could use generics:

 #region ParentItem
    public class BaseHeaderFooterItem<T>
        where T:class 
    {
        public string Title { get; set; }
        public string EnTitle { get; set; }
        public HyperLink Link { get; set; }
        public int Level { get; set; }
        public List<T> Descendants { get; set; }
    }
    #endregion

    #region HeaderFooter
    public class HeaderFooter : BaseHeaderFooterItem<Category>
    {
    }
    #endregion

    #region HeaderFooter
    public class Category : BaseHeaderFooterItem<Show>
    {
    }
    #endregion

    #region Header
    public class Show : HeaderFooter
    {
        public string ImagePath { get; set; }
        public string MobileLink { get; set; }
        public string MobileLinkTarget { get; set; }
    }
    #endregion

    #region TvGuid
    public class TvGuid : Show
    {
        public string Date { get; set; }
        public string Time { get; set; }
        public int IsActive { get; set; }
        public int NoProgram { get; set; }
    }
    #endregion