public class Father
{
public Father()
{
MessageBox.Show("Father is constructed.");
}
} public class Son : Father
{
public Son()
{
MessageBox.Show("Son is constructed.");
}
}
///////////////////////////////////////////////////
现在执行:
Son son=new Son();结果是:
Father is constructed.
Son is constructed.
即是说,在将Son自身实例化时,也调用的父类的构造函数。为什么呢?怎么样才能在Son son=new Son()时,不调用父类的构造函数?
{
public Father()
{
MessageBox.Show("Father is constructed.");
}
} public class Son : Father
{
public Son()
{
MessageBox.Show("Son is constructed.");
}
}
///////////////////////////////////////////////////
现在执行:
Son son=new Son();结果是:
Father is constructed.
Son is constructed.
即是说,在将Son自身实例化时,也调用的父类的构造函数。为什么呢?怎么样才能在Son son=new Son()时,不调用父类的构造函数?
yes.
怎么样才能在Son son=new Son()时,不调用父类的构造函数
You can not. Base constructor must be called either implicitly (your way) or explicitly (see the folowing example).
public class Son : Father
{
public Son() : base() //<--- explicity calls base constructor
{
MessageBox.Show("Son is constructed.");
}
}
如果父类构造函数有参数,实例化子类对象时,需要显示调用这个带参数的构造函数,不然编译时会出错。
这种初始化方式常用来对类中常量(const)成员进行初始化。