重写属性不起作用
本文关键字:不起作用 属性 重写 | 更新日期: 2023-09-27 18:18:54
我的类Ellipse
应该继承我的类Shape
,但我得到这个错误消息:
错误1 'ConsoleApplication3。"Ellipse"不实现继承的抽象成员"ConsoleApplication3.Shape.Perimeter.get"
我也得到错误信息,我隐藏Area
,在Ellipse
的属性。
我的shape类是这样的:
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;
}
}
}
你需要在椭圆类的面积和周长属性上使用override
修改器,例如
public override double Area { get; }
public override double Perimeter { get; }
在Visual Studio中给您一个提示,将光标放在文本"Shape"(在您的椭圆类中)并按Ctrl + .。这应该会为尚未实现的成员添加存根
可能这是你之后,因为你没有声明长度,宽度在你的椭圆类的任何地方,所以你可能会得到编译错误,编译这个你需要增强你的基类形状的_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;
}
}
}