使用更指定的返回类型(协方差)覆盖抽象属性 [英] Overriding abstract property using more specified return type (covariance)

查看:29
本文介绍了使用更指定的返回类型(协方差)覆盖抽象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.我怎样才能做到这一点?

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

推荐答案

您最初尝试完成的事情是不可能的 - .NET 不支持方法重载的 co(contra)variance.属性也是如此,因为属性只是方法对.

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

这篇关于使用更指定的返回类型(协方差)覆盖抽象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆