我無法使用基類構造函數將值分配給子類構造函數。你能幫我理解這一點嗎?初始化子類構造函數:繼承
代碼:
class Polygon
{
public int NumSides;
public Polygon (int numsides)
{
this.NumSides = 4;
}
}
class Square : Polygon
{
public readonly int SideLength;
public Square(int SideLength) : base(SideLength)
{
this.SideLength = NumSides;
}
}
class Program
{
static void Main(string[] args)
{
Polygon p = new Polygon(1);
Console.WriteLine("Polygon Class {0}", p.NumSides);
Square s = new Square(1);
Console.WriteLine("SquareClass {0}", s.SideLength);
Console.ReadLine();
}
}
結果:多邊形類:4,SquareClass:0
如果我修改於:
class Square : Polygon
{
public readonly int SideLength;
public Square(int SideLength) : base(SideLength)
{
this.SideLength = NumSides;
}
}
它的工作原理。
你確定你使用這段代碼得到了這個結果嗎? – user3185569
是不是你的修改代碼與原始代碼相同? – stuartd
輸出實際上是:多邊形類4,SquareClass 4 – stuartd