覆盖属性不起作用

时间:2011-12-26 22:33:09

标签: c#

我的班级Ellipse应该从我的班级Shape继承但我收到此错误消息:

  

错误1'ConsoleApplication3.Ellipse'未实现继承的抽象成员'ConsoleApplication3.Shape.Perimeter.get'

我还收到了我隐藏Area的错误消息,Ellipse中的属性。

有人可以帮我吗?

我的形状类看起来像这样:

public abstract class Shape
{
    //Protected constructor
    protected Shape(double length, double width)
    {
        _length = length;
        _width = width;
    }


    private double _length;
    private double _width;

    public abstract double Area
    {
        get;
    }

我的椭圆类是:

class Ellipse : Shape
{
    //Constructor
    public Ellipse(double length, double width)
        :base(length, width)
    {

    }

    //Egenskaper
    public override double Area
    {
        get
        {
            return Math.PI * Length * Width;
        }
    }
}

2 个答案:

答案 0 :(得分:5)

您需要在Ellipse类的Area和Perimeter属性中使用override修饰符,例如。

public override double Area { get; }

public override double Perimeter { get; }

在Visual Studio中为您提示,将光标放在文本'Shape'(在椭圆类中)并按 Ctrl + 。这应该为你尚未实现的成员添加存根

答案 1 :(得分:1)

可能这是你之后的事情,因为你没有在Ellipse类中的任何位置声明Length,Width所以你可能会遇到编译错误,为了编译它你需要增强基类Shape的_length和_width属性的可见性。

public abstract class Shape
{
  //Protected konstruktor
  protected Shape(double length, double width)
  {
    _length = length;
    _width = width;
  }

  // have these variables protected since you instantiate you child through the parent class.       

  protected double _length;
  protected double _width;

  public abstract double Area
  {
    get;
  }
}
class Ellipse : Shape
{
  //Konstruktor
  public Ellipse(double length, double width)
    : base(length, width)
  {

  }

  //Egenskaper
  public override double Area
  {
    get
    {
      // use the variable inherited since you only call the base class constructor.
      return Math.PI * _length * _width;
    }
  }
}