从事.NET开发接近两年了。对.NET这个东西依旧没有系统的去了解过。目前这份工作强度不太大,终于有时间可以捋一捋了。
1、普通构造函数:
abstract class Shape
{
public const double pi = Math.PI;
protected double x, y;
public Shape(double x, double y)
{
this.x = x;
this.y = y;
Console.WriteLine("shape()");
}
public abstract double Area();
}
如上所示:[访问修饰符] 类名 ([参数]){ [方法体] }
一个类可以有多个构造函数。只需参数不同(个数,类型)
2、继承时构造函数:
class Circle : Shape
{
public Circle(double radius)
// : base(10, 10)
: base(radius, 0)
{
Console.WriteLine("Circle()");
}
public override double Area()
{
Console.WriteLine("Circle()return");
return pi * x * x;
}
}
如上所示,如果父类构造函数必须有参数,在子类中需要将父类赋予参数进行实例化。
class Cylinder : Circle
{
public Cylinder(double radius, double height)
: base(radius)
{
Console.WriteLine("Cylinder()");
y = height;
}
public override double Area()
{
Console.WriteLine("Cylinder()return");
return (2 * base.Area()) + (2 * pi * x * y);
}
}
class TestShapes
{
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();
//Console.ReadKey();
Console.ReadLine();
}
}
本文中代码均摘自在线msdn。
执行
Circle ring = new Circle(radius);
时,首先跳转执行Circle的构造函数,进入Circle构造函数的方法体之前,进入Circle的父类Shape,调用Shape的构造函数进行处理。
即:从父类的构造函数开始按照继承关系逐次执行。
c#中,继承一个父类,可继承多个接口