【发布时间】:2016-11-19 10:07:55
【问题描述】:
我在理解以下代码 sn-p 中的一行时遇到问题(摘自本书:MCSD Certification Toolkit (Exam 70-483) Programming in C#)... 这里的问题集如下:
创建一个表示椭圆的 Ellipse 类。它应该将椭圆的大小和位置存储在 RectangleF 类型的 Location 属性中(在 System.Drawing 命名空间中定义)。给它两个构造函数:一个接受 RectangleF 作为参数,另一个接受 X 位置、Y 位置、宽度、 和高度作为参数。让第二个构造函数调用第一个构造函数,如果宽度或高度小于或等于0,则让构造函数抛出异常。
class Ellipse
{
public RectangleF Location { get; set; }
// Constructor that takes a RectangleF as a parameter.
public Ellipse(RectangleF rect)
{
// Validate width and height.
if (rect.Width <= 0)
throw new ArgumentOutOfRangeException("width", "Ellipse width must be greater than 0.");
if (rect.Height <= 0)
throw new ArgumentOutOfRangeException("height", "Ellipse height must be greater than 0.");
// Save the location.
Location = rect;
}
// Constructor that takes x, y, width, and height as parameters.
public Ellipse(float x, float y, float width, float height)
: this(new RectangleF(x, y, width, height))
{
}
}
我在理解以下行时遇到问题... 谁能解释下一行的作用?请解释得详细一点!
:this(new RectangleF(x, y, width, height))
提前致谢!
【问题讨论】:
-
:this(new RectangleF(x, y, width, height))调用public Ellipse(RectangleF rect)构造函数。基本上,您的椭圆要么由x, y, width and height构造而成,要么由rectangle构造而成。当您从x, y, width and height构造它时,您将它们作为构造rectangle的参数传递,该rectangle作为参数传递给您的其他构造函数。最后,您只使用了一个构造函数——一个接受rectangle,另一个只是将您“重定向”到它(将矩形参数转换为矩形) -
这样你就不必重复其他构造函数的逻辑了。
标签: c# inheritance constructor