我希望我的默认构造函数创建和初始化我的代码片段中显示的所有对象。然后我希望我的参数化构造函数调用默认构造函数,从而创建和初始化这些对象,然后可以在参数化构造函数中使用这些对象,而不会出现 NullReferenceException。
在这种情况下,我不确定使用构造函数的最佳(最有效、更少代码等)方法是什么。我更喜欢使用构造函数链接。
同样,我对构造函数有一个非常基本的了解,所以如果这不可能,那么请告诉我,告诉我在这种情况下你会做什么。
class Rectangle
{
public Line left { get; set; }
public Line top { get; set; }
public Line right { get; set; }
public Line bottom { get; set; }
public Rectangle() : this(new Line()) { }
public Rectangle(Line diagnonal)
{
left = new Line();
top = new Line();
right = new Line();
bottom = new Line();
Point beginningDiagonalPoint = new Point();
Point endingDiagonalPoint = new Point();
beginningDiagonalPoint = diagnonal.startPoint;
endingDiagonalPoint = diagnonal.endPoint;
int begXC = beginningDiagonalPoint.xCoord;
int begYC = beginningDiagonalPoint.yCoord;
int endXC = endingDiagonalPoint.xCoord;
int endYC = endingDiagonalPoint.yCoord;
Point rightSideEnd = new Point();
rightSideEnd.xCoord = endXC;
rightSideEnd.yCoord = begYC;
Point leftSideEnd = new Point();
leftSideEnd.xCoord = begXC;
leftSideEnd.yCoord = endYC;
// ----------- right side definitions -------------
right.startPoint = endingDiagonalPoint;
right.endPoint = rightSideEnd;
// ------------ left side definitions --------------
left.startPoint = beginningDiagonalPoint;
left.endPoint = leftSideEnd;
// ------------ top side definitions -------------
top.startPoint = leftSideEnd;
top.endPoint = endingDiagonalPoint;
// ------------ bottom side definitions -----------
bottom.startPoint = rightSideEnd;
bottom.endPoint = beginningDiagonalPoint;
}
}