如何使此代码以不同的方式进行
本文关键字:方式进 何使此 代码 | 更新日期: 2023-09-27 18:31:12
下面的代码是我的面试问题,但我不知道如何做到完美
法典:
public class Shape
{
public void Rectangle(int length, int height)
{
Console.Write(length * height);
}
public void Circle(int radius)
{
Console.Write(3.14 * (radius * radius));
}
}
有什么想法吗?提前致谢
怎么样?
public abstract class Shape
{
public abstract int CalcArea();
}
public class Rectangle : Shape
{
public int Height { get; set; }
public int Width { get; set; }
public override int CalcArea()
{
return Height * Width;
}
}
public class Circle : Shape
{
public float Radius { get; set; }
public override int CalcArea()
{
return Math.PI * (Radius * Radius);
}
}
-
使
Shape
成为接口或抽象类 -
声明一个抽象方法
getArea()
Shape
-
使
Shape
的子类Rectangle
和Circle
,Rectangle
具有高度和宽度,Circle
具有半径。 -
在
Rectangle
和Circle
中实现getArea()
(在Rectangle
中返回 h*w,在Circle
中返回 π*r2)