Overriding abstract property using more specified return type (covariance)

前端 未结 1 380
情深已故
情深已故 2020-12-21 17:13
class Base {}

abstract class A
{
    abstract public List Items { get; set; }
}

class Derived : Base {}

class B : A
{ 
    private List         


        
相关标签:
1条回答
  • 2020-12-21 17:52

    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;
               }
          }
      }
    
    0 讨论(0)
提交回复
热议问题