C# 重新定义列表';s内容类型
好吧,在严格类型编程语言中,这可能是另一个愚蠢的问题,但是C# 重新定义列表';s内容类型,c#,list,C#,List,好吧,在严格类型编程语言中,这可能是另一个愚蠢的问题,但是 public class Parent { public List<Parent> list_of = new List<Parent>; } public class Child : Parent { public List<Child> list_of = new List<Child>; } 公共类父类 { 公共列表=新列表; } 公共类子级:父级 { 公共列表=
public class Parent
{
public List<Parent> list_of = new List<Parent>;
}
public class Child : Parent
{
public List<Child> list_of = new List<Child>;
}
公共类父类
{
公共列表=新列表;
}
公共类子级:父级
{
公共列表=新列表;
}
基本上,我想问的是,是否可以更改儿童课程中列表的“内容”类型?基本上,否。关于覆盖:
- 无法覆盖字段
- 您可以重写
属性或函数虚拟
- 重写任何内容时不能更改类型(即使是泛型类型的类型参数)
new
关键字隐藏字段/属性/函数并更改类型:
public class Parent
{
public List<Parent> ListOf = new List<Parent>();
}
public class Child : Parent
{
public new List<Child> ListOf = new List<Child>();
}
但即使在那里,在重写时也不能将属性类型
IEnumerable
更改为IEnumerable
。现在我想起来了,在这些类中只需有两个单独的列表就可以了。但是“覆盖”/“重新定义”的问题仍然存在。您可以将其保留为列表,并且在其中存储子实例仍然有效,您可以使用List_of.OfType将它们作为子实例返回
public class Parent
{
public virtual IEnumerable<Parent> ListOf { get; set; } = new List<Parent>();
}
public class Child : Parent
{
public override IEnumerable<Parent> ListOf { get; set; } = new List<Child>();
}