[英]How to inherit parent constants and access them?
如何從父 class 訪問 const 變量?
我有一個 PI 常量,我想在 TCylinder class 中使用它,如何訪問它? 我知道我可以使用 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
}
}
您沒有為該屬性指定訪問修飾符,因此它將默認為private
。 改用protected
的,繼承它的類可以看到它。
正如 Moo-Juice 所說,如果你給常量一個訪問修飾符而不是private
,那就沒問題了。
但是,我會推薦一些稍微不同的東西:完全擺脫常量。 它已經存在(以更精確的形式)在System.Math
中。 如果您添加以下內容,則可以無條件使用它:
using static System.Math;
在每個源文件的頂部。
作為其他建議:
T
前綴我會使用自動實現的屬性,而不是手動實現的帶有單獨字段的屬性:
public double Radius { get; set; }
然后在任何地方使用該屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.