我想知道我们是否可以隐藏in 的public
属性。Base Class
Derived Class
我有以下用于计算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
其基类的方法Rectangle
。在现实世界中,如果发生这种类型的继承该方法逻辑可能更复杂)