我无法使用基类构造函数将值赋给子类构造函数。你能帮我理解吗?
代码:
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();
}
}
结果:Polygon Class:4,SquareClass:0
如果我修改为:
class Square : Polygon
{
public readonly int SideLength;
public Square( int SideLength) : base(SideLength)
{
this.SideLength = NumSides;
}
}
有效。
答案 0 :(得分:0)
我认为你正在混淆NumSides(Polygon基类的一部分)和SideLength(仅限Square)。
我猜你想要那些课程:
class Polygon
{
public int NumSides;
public Polygon(int numsides)
{
this.NumSides = numsides;
}
}
class Square : Polygon
{
public readonly int SideLength;
public Square(int SideLength) : base(4)
{
this.SideLength = SideLength;
}
}
即在Polygon构造函数中指定NumSides,在Square构造函数中指定SideLength - 但将NumSides的4传递给Square中的基础构造函数。
希望有所帮助。