I have a class
public class BaseHeaderFooterItem
{
public string Title { get; set; }
public string EnTitle { get; set; }
public HyperLink Link { get; set; }
public int Level { get; set; }
public HyperLink MobileLink { get; set; }
}
Many other class inherit from him I want to have on generic list in the class BaseHeaderFooterItem that will be able to hold a list from any type of the inherited classes. something like this:
public class BaseHeaderFooterItem
{
public string Title { get; set; }
public string EnTitle { get; set; }
public HyperLink Link { get; set; }
public int Level { get; set; }
public HyperLink MobileLink { get; set; }
public List<T> Descendants { get; set; }
}
How can I do it ?
You could try to keep a properties to hold a child collection of the base type.
public class BaseHeaderFooterItem
{
public string Title { get; set; }
public string EnTitle { get; set; }
public HyperLink Link { get; set; }
public int Level { get; set; }
public HyperLink MobileLink { get; set; }
// here you can add instances of BaseHeaderFooterItem and any inherits type
public List<BaseHeaderFooterItem> Descendants { get; set; }
}
And you could add any tpe that inherits from BaseHeaderFooterItem
, for sample:
var list = new List<BaseHeaderFooterItem>();
list.Add(new BaseHeaderFooterItem() {
Title = "Test"
Descendants = new List<BaseHeaderFooterItem>()
{
new ChildHeaderFooterItem() { /* properties */}
}
});
Or if you need a specif type for each BaseHeaderFooterItem
, than try to specif the generic on the declaration.
public class BaseHeaderFooterItem<T>
where T : BaseHeaderFooterItem<T>
{
public string Title { get; set; }
public string EnTitle { get; set; }
public HyperLink Link { get; set; }
public int Level { get; set; }
public HyperLink MobileLink { get; set; }
// only T types
public List<T> Descendants { get; set; }
}
var list = new List<BaseHeaderFooterItem<ChildType>>();
list.Add(new BaseHeaderFooterItem() {
Title = "Test"
Descendants = new List<ChildType>()
{
new ChildHeaderFooterItem() { /* properties */}
}
});
You may use this pattern
public interface IBaseHeaderFooterItem
{
string Title { get; set; }
string EnTitle { get; set; }
public HyperLink Link { get; set; }
int Level { get; set; }
HyperLink MobileLink { get; set; }
}
public abstract class BaseHeaderFooterItem<T> : IBaseHeaderFooterItem
where T : IBaseHeaderFooterItem
{
public List<T> Descendants { get; set; }
public abstract string Title { get; set; }
public abstract string EnTitle { get; set; }
public abstract HyperLink Link { get; set; }
public abstract int Level { get; set; }
public abstract HyperLink MobileLink { get; set; }
}
Then you can inherit from BaseHeaderFooterItem<T>
and T is constraint to be a class implementing IBaseHeaderFooterItem
and having all those properties.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.