我正在阅读一个简单继承的示例,并偶然发现了一个基本概念,即正方形是基本类型,而矩形是从正方形派生的。
设置正方形尺寸的示例使用了一个名为 Size
的属性。
矩形示例然后继续使用 Width
和 Height
。
这在我的脑海中没有意义,所以我对其进行了编码。
问题似乎是在访问 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/