正确使用C#继承

时间:2016-07-24 10:07:57

标签: c#

我已经编写了下面的代码,但是我看到为了访问最后一个子节点的宽度和长度是badRectangle是通过覆盖从Rectangle和shape类中入侵的所有内容,这意味着我必须复制输入和ii有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;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

这将是在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;
        }
    }
}

答案 1 :(得分:0)

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