c# - C# 中的不良继承示例

标签 c# inheritance

我正在阅读一个简单继承的示例,并偶然发现了一个基本概念,即正方形是基本类型,而矩形是从正方形派生的。

设置正方形尺寸的示例使用了一个名为 Size 的属性。 矩形示例然后继续使用 WidthHeight

这在我的脑海中没有意义,所以我对其进行了编码。

问题似乎是在访问 rectangle 时,总是会出现一个名为“Size”的令人困惑的属性。

我做对了吗?或者有没有办法在查看 rectangle 时隐藏其他类以防止看到 Size

public class square
{
    public int Size { get; set; }
    public square(int size)
    {
        this.Size = size;
    }
}

public class rectangle : square
{
    public int Width { get { return base.Size; } set { base.Size = value; } }

    public int Height { get; set; }

    public rectangle(int width, int height)
        : base(width)
    {
        Height = height;
    }
}

最佳答案

你是 100% 正确的,这是向后继承。相反,您应该让 Square 类继承自 Rectangle 类,因为正方形是一种特殊的矩形。

然后,你会得到类似的东西

public class Rectangle
{
    public int Width { get; private set; }
    public int Height { get; private set; }

    public Rectangle(int width, int height)
    {
        if (width <= 0 || height <= 0)
            throw new ArgumentOutOfRangeException();
        Width = width;
        Height = height;
    }
}

public class Square : Rectangle
{
    public int Size
    {
        get
        {
            return Width;
        }
    }

    public Square(int size)
        : base(size, size)
    {
    }
}

关于c# - C# 中的不良继承示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9320214/

相关文章:

c# - 将字符串转换为 DateTime 对象

c# - 更改系统托盘颜色 Windows Phone

c++ - 链接错误 C++ 继承

php - 在 PHP 父类(super class)的静态方法中访问子类的静态属性的正确方法是什么?

java - TestNG 中的继承和@BeforeSuite

c# - 无法识别发送到 SQL Server 存储过程的参数

c# - 使用多重匹配和通配符查询

c# - 如何使用 Entity Framework 和 Identity 解决对象处置异常 ASP.NET Core

Swift:初始化程序不会覆盖其父类(super class)中的指定初始化程序

c++ - 如何从普通bst继承红黑树