【发布时间】:2013-06-03 18:53:23
【问题描述】:
我想知道我们是否可以在Derived Class 中隐藏Base Class 的public 属性。
我有以下示例问题语句用于计算不同形状的Area -
abstract class Shape
{
public abstract float Area();
}
class Circle : Shape
{
private const float PI = 3.14f;
public float Radius { get; set; }
public float Diameter { get { return this.Radius * 2; } }
public Circle() { }
public Circle(float radius)
{
this.Radius = radius;
}
public override float Area()
{
return PI * this.Radius * this.Radius;
}
}
class Triangle : Shape
{
public float Base { get; set; }
public float Height { get; set; }
public Triangle() { }
public Triangle(float @base, float height)
{
this.Base = @base;
this.Height = height;
}
public override float Area()
{
return 0.5f * this.Base * this.Height;
}
}
class Rectangle : Shape
{
public float Height { get; set; }
public float Width { get; set; }
public Rectangle() { }
public Rectangle(float height, float width)
{
this.Height = height;
this.Width = width;
}
public override float Area()
{
return Height * Width;
}
}
class Square : Rectangle
{
public float _side;
public float Side
{
get { return _side; }
private set
{
_side = value;
this.Height = value;
this.Width = value;
}
}
// These properties are no more required
// so, trying to hide them using new keyword
private new float Height { get; set; }
private new float Width { get; set; }
public Square() : base() { }
public Square(float side)
: base(side, side)
{
this.Side = side;
}
}
现在有趣的部分是在Square 类中Height 和Width 属性不再需要(因为它被Side 属性替换)来暴露于外部世界所以我使用new 关键字隐藏它们。但它不起作用,用户现在可以设置 Height 和 Width -
class Program
{
static void Main(string[] args)
{
Shape s = null;
// Height & Width properties are still accessible :(
s = new Square() { Width = 1.5f, Height = 2.5f };
Console.WriteLine("Area of shape {0}", s.Area());
}
}
有谁知道在 C# 中可以隐藏派生类的不需要的属性吗?
重要提示:
有人可能会指出Shape -> Rectangle -> Square 不是一种合适的继承设计。但我想保持这种状态,因为我不想在Square 类中再次编写“不精确”但类似的代码(注意:Square 类使用其基类Area 的Area 方法@ .在现实世界中,如果是这种类型的继承,方法逻辑可能会更复杂)
【问题讨论】:
-
与其向我们展示您知道错误的设计示例,不如向我们询问您的实际情况?
-
您尝试做的事情没有多大意义。如果你没有 Square 对象中的 Height 和 Width 属性,那么 Square 应该继承自 Shape,而不是 Rectangle。
-
@Oded 是的,在形状的情况下确实如此。但它会在
Rectangle和Shape中重复计算Area的逻辑。从理论上讲,每个人都知道 [b]Square是Rectangle[/b]。从逻辑上讲,我们应该从Rectangle继承Square。除了形状之外,我们可能会在real wold examples中找到这种情况。那么这个共同的逻辑就会被复制。我的问题就是这个。 -
有一个东西叫做'protected'
-
“每个人都知道 [b]Square 是一个 Rectangle[/b]”。我不同意,我认为这就是你的模型崩溃的原因。我认为更好的设计是
Shape -> ConvexPolygon -> RegularConvexPolygon ->Square和Shape -> ConvexPolygon -> Rectangle。这样一来,所有 RegularConvexPolygons 都可以共享 Area 计算(如果您的语言支持计算无穷大的限制,则一直到 Circle)。
标签: c# oop design-patterns inheritance