隐藏派生类中基类的公共属性

Par*_*ram 2 c# oop inheritance design-patterns

我想知道我们是否可以隐藏in的public属性.Base ClassDerived 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在有趣的部分是在Square类Height和Width属性中不再需要(因为它被Side属性替换)以暴露给外部wold所以我使用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());
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有人知道在C#中是否可以隐藏不需要的派生类的属性?

重要说明: 有人可能会指出,这Shape -> Rectangle -> Square不是一种合适的继承设计.但我想保持这种方式,因为我不想在类中再写"不完全"但类似的代码Square(注意:Square类使用Area其基类的方法Rectangle.在现实世界中,如果是这种类型的继承那个方法逻辑可能会更复杂)

Mar*_*ell 5

任何子类型仍然基本上能够被处理为基类型的实例.如果某人有一个类型为基类型的变量,你肯定无法隐藏成员.你能做的最多就是在使用派生类型时使它们真的很烦人,例如:

[Obsolete, Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new float Width { get { return base.Width;} }
Run Code Online (Sandbox Code Playgroud)

您也可以执行类似的操作override,甚至可能使用不当throw的访问器(set特别是).

但是,听起来更像是应该更改继承模型,以便您永远不想尝试删除成员.