正确利用C#继承

本文关键字:继承 | 更新日期: 2023-09-27 17:58:28

我已经写了下面的代码,但我发现,要访问最后一个子项的宽度和长度,即badRectangle,需要重写Rectangle和shape类中的所有内容,这意味着我必须复制输入,并且我有6个或更多级别的继承,代码会有点混淆和重复很多事情。

这段代码工作正常,但却是处理C#中继承的正确方法。

class Program
{
    static void Main(string[] args)
    {
       badRectangle myRect = new badRectangle(true,"Rectangle",23.0,23);
       Console.WriteLine("The Area of your Rectangle = " + myRect.getArea().ToString()
           + "'nAnd " + myRect.getStatus());
       Console.ReadLine();
    }
    public abstract class shape
    {
        string type;
        public abstract double getArea();
        public shape(string type)
        {
            this.type = type;
        }
    }
    public class rectangle : shape
    {
        double width, length;
        public rectangle(string type, double width, double length):base(type)
        {
            this.width = width;
            this.length = length;
        }
        public override double getArea()
        {
            return width * length;    
        }
    }
    public class badRectangle : rectangle
    {
        double width, length;
        bool badOrNot = false;
        public badRectangle(bool badOrNot,string type, double width, double length):base(type,width,length)
        {
            this.badOrNot = badOrNot;
            this.width = width;
            this.length = length;
        }
        public string getStatus()
        {
            string answer = "No, Rectangle is not bad";
            if (badOrNot == true)
            {
                answer = "Yes, Rectangle is bad";
            }
                return answer;
        }
        public override double getArea()
        {
            return width * length;
        }
    }
}

正确利用C#继承

这将是C#中"正确"或传统的方法:

public abstract class Shape
{
    public string Type { get; private set; }
    public abstract double Area { get; }
    public Shape(string type)
    {
        this.Type = type;
    }
}
public class Rectangle : Shape
{
    public double Length { get; private set; }
    public double Width { get; private set; }
    public Rectangle(string type, double width, double length)
        : base(type)
    {
        this.Width = width;
        this.Length = length;
    }
    public override double Area { get { return this.Width * this.Length; } }
}
public class BadRectangle : Rectangle
{
    public bool BadOrNot { get; private set; } = false;
    public BadRectangle(string type, double width, double length, bool badOrNot)
        : base(type, width, length)
    {
        this.BadOrNot = badOrNot;
    }
    public string Status
    {
        get
        {
            string answer = "No, Rectangle is not bad";
            if (this.BadOrNot == true)
            {
                answer = "Yes, Rectangle is bad";
            }
            return answer;
        }
    }
}

您不需要在派生类中再次设置widthlength,只需将它们传递给基类的构造函数即可。如果需要在派生类中访问它们,请将它们设为protected。如果getArea()做了同样的事情,就不必重写它。