Square上的构造函数需要设置自己的参数,并且参数继承自父类Polygon。
class Polygon
{
public int NumSides;
public Polygon(int numSides)
{
NumSides = numSides;
}
}
class Square : Polygon
{
public int SideLength;
public Square (int sideLength) : this(numSides) : base(numSides)
{
SideLength = sidelength;
NumSides = NumSides;
}
}
答案 0 :(得分:2)
public Square (int sideLength)
//: this(numSides) // would call this ctor again, an endless loop
: base(4) // because a square has 4 sides
{
SideLength = sidelength;
// NumSides = NumSides; // action already taken in the base class
}
答案 1 :(得分:1)
要传递给基类的参数必须是子类的ctor的一部分:
class Square : Polygon {
public int SideLength;
public Square (int sideLength, int numSides) : base(numSides) {
SideLength = sidelength;
// NumSides will be handled by base class ctor
}
// ctor overload with fixed number of sides for squares
public Square (int sideLength) : this(sideLength, 4) {
}
}