c# - 方法中的冒号
问题描述
只是想在一个方法中确认我对冒号的理解。我发现这篇文章解释了冒号之后的代码在被调用的方法之前运行。
这是否意味着在下面的代码中 Shape 在 Circle 之前运行?而Circle在Cylinder之前运行?
public abstract class Shape
{
public const double pi = Math.PI;
protected double x, y;
public Shape(double x, double y) => (this.x, this.y) = (x, y);
public abstract double Area();
}
public class Circle : Shape
{
public Circle(double radius) : base(radius, 0) { }
public override double Area() => pi * x * x;
}
public class Cylinder : Circle
{
public Cylinder(double radius, double height) : base(radius) => y = height;
public override double Area() => (2 * base.Area()) + (2 * pi * x * y);
}
public class TestShapes
{
private static void Main()
{
double radius = 2.5;
double height = 3.0;
Circle ring = new Circle(radius);
Cylinder tube = new Cylinder(radius, height);
Console.WriteLine("Area of the circle = {0:F2}", ring.Area());
Console.WriteLine("Area of the cylinder = {0:F2}", tube.Area());
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Output:
Area of the circle = 19.63
Area of the cylinder = 86.39
*/
解决方案
对于构造函数(与类名同名的函数名), : 表示将调用基类的构造函数,并在子构造函数的代码之前使用任何传递的参数首先执行。
所以对于函数public Cylinder(double radius, double height) : base(radius)
来说,Circle 的构造函数在 Cylinder 构造函数中的代码之前执行,后者依次调用 Shape 设置的构造函数this.x
和this.y
,然后执行它自己的代码,它没有,最后 Cylinder 构造函数中的代码是执行,设置y
。