gpt4 book ai didi

c# - 在派生类中隐藏基类的公共(public)属性

转载 作者:行者123 更新时间:2023-11-30 19:17:38 24 4
gpt4 key购买 nike

我想知道我们是否可以隐藏 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关键字来隐藏它们。但它不起作用,用户现在可以设置 HeightWidth -

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 类使用其基类AreaRectangle 方法。在现实世界中,在这种类型的继承的情况下,方法逻辑可能会更复杂)

最佳答案

任何子类型基本上仍然能够被视为基本类型的实例。如果某人有一个变量类型为基本类型,您当然不能隐藏成员。您最多可以做的就是让它们在使用派生类型时变得非常烦人,例如:

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

您也可以使用 override 做一些类似的事情,如果访问器(特别是 set)使用不当,甚至可以使用 throw

但是,这听起来更像是您应该更改继承模型,这样您就永远不想尝试删除成员。

关于c# - 在派生类中隐藏基类的公共(public)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16984548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com