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

问题描述

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必须是匹配匹配的重写成员" A.Items的基本元素列表.我该怎么做?

解决方案

最初尝试完成的工作是不可能的-.属性也是一样,因为属性只是这对方法. /p>

但是您可以使您的类通用:

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

解决方案

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

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

07-24 04:40