Overriding abstract property using more specified

2020-02-15 02:01发布

问题:

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;
           }
      }
  }

The compiler says that B.Items must be List of Base elements "to match overridden member" A.Items. How can i make that work?

回答1:

What you've tried to accomplish initially is impossible - .NET does not support co(contra)variance for method overload. The same goes for properties, because properties are just the pair of methods.

But you can make your classes generic:

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;
           }
      }
  }