首先说明下之所以用双引号是因为构造函数是没有继承的派生类默认会调用基类的无参数构造函数
比如:
public class A {
public A() {
ConsoleWriteLine(A);
}
public A(string name) {
ConsoleWriteLine(A Name:{} name);
}
}
public class B : A {
public B() {
ConsoleWriteLine(B);
}
public B(string name) {
ConsoleWriteLine(B Name:{} name);
}
}
class Program
{
static void Main(string[] args)
{
B b = new B();
B b = new B(张三);
ConsoleReadKey();
}
}
输出的结果为
说明不管调用派生类的哪个构造函数默认都先调用基类的无参数构造函数
之所以标题中用 继承 是因为构造函数之间的调用也是用 :下面就在派生类里面调用一下基类的构造函数
class Program {
static void Main(string[] args)
{
B b = new B();
ConsoleReadKey();
}
}
public class B : A {
public B():base(B>A) {
ConsoleWriteLine(B);
}
public B(string name) {
ConsoleWriteLine(B Name:{} name);
}
}
输出结构为
由结果可以看出当给B的构造函数手动指派要调用的基类带参数的构造函数后将不再执行基类的无参数构造函数
下面写下在同一个类中构造函数的调用
class Program {
static void Main(string[] args)
{
B b = new B();
ConsoleReadKey();
}
}
public class B : A {
public B():this(无惨>带参) {
ConsoleWriteLine(B);
}
public B(string name):this(true) {
ConsoleWriteLine(B Name:{} name);
}
public B(bool b) {
ConsoleWriteLine(B bool:{} b); }
}
输出结果
为了看一下调用的先后关系就又加了一个bool参数的构造函数由结果可以看出如果构造函数调用了另一个构造函数例如
public B():this(无惨>带参)
执行顺序是从后向前依次执行的