Overriding abstract property using more specified return type (covariance)

假装没事ソ 提交于 2019-12-29 09:08:11

问题


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


来源:https://stackoverflow.com/questions/24561023/overriding-abstract-property-using-more-specified-return-type-covariance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!