简体   繁体   中英

Calling the base class directly in the derived class constructor argument

I have 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;        
    }
}

Essentially, I am hoping to add one more constructor to LineSegmentGeometry that goes something like this:

LineSegmentGeometry(Point endPoint, LineGeometry l)
{
    this.startPoint = l.startPoint;
    this.direction = l.direction;      
    this.endPoint = endPoint;
}

Since essentially LineSegmentGeometry is exactly the same as its base class, with the exception of 1 additional variable.

However the compiler throws an error that the base class is inaccessible due to its protection level. Is this way of declaring the constructor a good idea and if it is okay, how do I go about resolving the error?

It sounds like you should just call up to the base class constructor:

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

Note that I'm referring to StartPoint and Direction as properties - I'd expect the fields to be private, but there to be public or internal properties exposing the values. If there aren't, then you could add a LineGeometry(LineGeometry) constructor, and use : base(l) instead, and let that copy the fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM