如何从父类访问const变量?
我有一个 PI 常量,我想在 TCylinder 类中使用它,我该如何访问它?我知道我可以使用 Math.PI,但为了将来我想知道
class TCircle {
const double PI = 3.14;
private double radius;
public double Radius { get => radius; set => radius = value; }
public TCircle(double radius)
{
this.radius = radius;
}
public virtual double GetArea()
{
return PI * this.radius * this.radius;
}
class TCylinder : TCircle {
private double height;
public TCylinder(double radius, double height)
: base(radius)
{
this.height = height;
}
public override double GetArea()
{
return (2 * base.GetArea()) + (2 * PI * height);//want to access PI
}
最佳答案
正如 Moo-Juice 所说,如果您为常量提供一个不同于 private
的访问修饰符,就可以了。
但是,我建议做一些稍微不同的事情:完全摆脱常量。它已经存在于 System.Math
中(以更精确的形式)。如果您添加:
using static System.Math;
在每个源文件的顶部。
作为其他建议:
- 我会关注 .NET naming conventions , 放弃
T
前缀 我会使用自动实现的属性,而不是带有单独字段的手动实现的属性:
public double Radius { get; set; }
然后到处使用这个属性。
- 考虑改为不可变类型。在不知道您如何使用它们的情况下,我们无法判断这是否可行,但至少值得考虑。
- 考虑更改您的继承模型 - 目前您说的是将圆柱体当作圆形来处理是可以的,而且我希望很少有东西可以真正与 3D 一起工作当他们期望 2D 形状时是实心的。
关于c# - 如何继承父常量并访问它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58506547/