如何使此代码以不同的方式进行

本文关键字:方式进 何使此 代码 | 更新日期: 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的子类RectangleCircleRectangle具有高度和宽度,Circle具有半径。

  • RectangleCircle中实现getArea()(在 Rectangle 中返回 h*w,在 Circle 中返回 π*r2