语法:
public DerivedClass ():base(){}
**tips: ** 如果不显式声明调用父类的无参构造函数(base()),那么默认会调用父类的无参构造函数。
无参 Example
class BaseClass
{
public BaseClass() {
Console.WriteLine("BaseClass");
}
}
class DerivedClass:BaseClass
{
public DerivedClass ():base() { // 因为是无参数,所以`:base()`默认可以不写
Console.WriteLine("DerivedClass");
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass derived = new DerivedClass();
// 先调用base的构造方法,再调用子类的构造方法
Console.ReadKey();
}
}
有参数Example:
class BaseClass
{
private int x;
public BaseClass() {
Console.WriteLine("BaseClass");
}
public BaseClass(int x) {
this.x = x;
}
}
class DerivedClass:BaseClass
{
private int y;
public DerivedClass ():base() {
Console.WriteLine("DerivedClass");
}
public DerivedClass(int x, int y) : base(x) { // `base中的x就是前面的x`
this.y = y;
Console.WriteLine("x=" + x + ", y=" + y);
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass initDerived = new DerivedClass(5, 10);
Console.ReadKey();
}
}