在派生的 class 构造函数参数中直接调用基础 class
Calling the base class directly in the derived class constructor argument
我有 2 个 classes:
public class LineGeometry
{
public LineGeometry(Point startPoint, Vector direction)
{
this.startPoint = startPoint; this.direction = direction;
}
}
public class LineSegmentGeometry : LineGeometry
{
Point endPoint;
public LineSegmentGeometry(Point startPoint, Point endPoint, Vector direction) : base (startPoint, direction)
{
this.startPoint = startPoint; this.direction = direction; this.endPoint = endPoint;
}
}
本质上,我希望向 LineSegmentGeometry
添加一个构造函数,如下所示:
LineSegmentGeometry(Point endPoint, LineGeometry l)
{
this.startPoint = l.startPoint;
this.direction = l.direction;
this.endPoint = endPoint;
}
因为本质上 LineSegmentGeometry
与其基础 class 完全相同,除了 1 个附加变量。
然而,编译器会抛出一个错误,指出基 class 由于其保护级别而无法访问。这种声明构造函数的方式是否是个好主意?如果可以,我该如何解决错误?
听起来你应该调用基础 class 构造函数:
LineSegmentGeometry(Point endPoint, LineGeometry l)
: base(l.StartPoint, l.Direction)
{
this.endPoint = endPoint;
}
请注意,我将 StartPoint
和 Direction
称为属性 - 我希望 字段 是私有的,但public 或内部 properties 公开值。如果没有,那么您可以添加一个 LineGeometry(LineGeometry)
构造函数,并改用 : base(l)
,然后让 that 复制字段。
我有 2 个 classes:
public class LineGeometry
{
public LineGeometry(Point startPoint, Vector direction)
{
this.startPoint = startPoint; this.direction = direction;
}
}
public class LineSegmentGeometry : LineGeometry
{
Point endPoint;
public LineSegmentGeometry(Point startPoint, Point endPoint, Vector direction) : base (startPoint, direction)
{
this.startPoint = startPoint; this.direction = direction; this.endPoint = endPoint;
}
}
本质上,我希望向 LineSegmentGeometry
添加一个构造函数,如下所示:
LineSegmentGeometry(Point endPoint, LineGeometry l)
{
this.startPoint = l.startPoint;
this.direction = l.direction;
this.endPoint = endPoint;
}
因为本质上 LineSegmentGeometry
与其基础 class 完全相同,除了 1 个附加变量。
然而,编译器会抛出一个错误,指出基 class 由于其保护级别而无法访问。这种声明构造函数的方式是否是个好主意?如果可以,我该如何解决错误?
听起来你应该调用基础 class 构造函数:
LineSegmentGeometry(Point endPoint, LineGeometry l)
: base(l.StartPoint, l.Direction)
{
this.endPoint = endPoint;
}
请注意,我将 StartPoint
和 Direction
称为属性 - 我希望 字段 是私有的,但public 或内部 properties 公开值。如果没有,那么您可以添加一个 LineGeometry(LineGeometry)
构造函数,并改用 : base(l)
,然后让 that 复制字段。