class Base {}
abstract class A
{
abstract public List<Base> Items { get; set; }
}
class Derived : Base {}
class B : A
{
private List<Derived> items;
public override List<Derived> Items
{
get
{
return items;
}
set
{
items = value;
}
}
}
编译器说B.Items必须是基本元素列表&#34;匹配被覆盖的成员&#34; A.Items。我怎样才能做到这一点?
答案 0 :(得分:4)
你最初想要完成的事情是不可能的 - .NET does not support co(contra)variance for method overload。属性也是如此,因为属性只是the pair of methods。
但是你可以让你的课程变得通用:
class Base {}
abstract class A<T>
where T : Base
{
abstract public List<T> Items { get; set; }
}
class Derived : Base {}
class B : A<Derived>
{
private List<Derived> items;
public override List<Derived> Items
{
get
{
return items;
}
set
{
items = value;
}
}
}