【问题标题】:Calling the base class directly in the derived class constructor argument在派生类构造函数参数中直接调用基类
【发布时间】:2015-02-11 08:29:59
【问题描述】:

我有 2 节课:

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 与其基类完全相同,只是多了一个变量。

但是编译器会抛出一个错误,即基类由于其保护级别而无法访问。这种声明构造函数的方式是个好主意吗?如果可以,我该如何解决错误?

【问题讨论】:

  • 顺便说一句,我强烈建议坚持每行一个语句。它使阅读更容易。此外,目前您的类声明无效(您不想要那些 ())并且您的 LineSegmentGeometry 类不是从 LineGeometry 派生的。
  • 感谢编辑错误

标签: c# inheritance


【解决方案1】:

听起来你应该只调用基类构造函数:

LineSegmentGeometry(Point endPoint, LineGeometry l)
    : base(l.StartPoint, l.Direction)
{
    this.endPoint = endPoint;
}

请注意,我将 StartPointDirection 称为属性 - 我希望 fields 是私有的,但会有公共或内部 properties em> 暴露值。如果没有,那么您可以添加一个LineGeometry(LineGeometry) 构造函数,并改用: base(l),然后让那个复制字段。

【讨论】:

    猜你喜欢
    • 2016-07-19
    • 2018-07-21
    • 2015-08-18
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 2014-03-26
    • 2020-11-28
    相关资源
    最近更新 更多