【问题标题】:Overriding abstract property using more specified return type (covariance)使用更指定的返回类型(协方差)覆盖抽象属性
【发布时间】:2014-08-25 00:13:45
【问题描述】:
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 必须是 Base 元素列表“以匹配被覆盖的成员”A.Items。我怎样才能做到这一点?

【问题讨论】:

    标签: c# c#-4.0 overriding abstract covariance


    【解决方案1】:

    你最初尝试完成的事情是不可能的 - .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;
               }
          }
      }
    

    【讨论】:

    • 但您可以对 only-set 或 only-get 属性使用协方差。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    相关资源
    最近更新 更多