特点:在子类对象实例化时,默认会先调用父类的构造函数,一直往上找父亲。从老祖宗开始执行,一代一代往下。
例子:
class GameObject
{
public GameObject()
{
Console.WriteLine("物体位置");
}
}
class Animal : GameObject
{
public Animal()
{
Console.WriteLine("动物来了");
}
}
class Tree : Animal
{
public Tree()
{
Console.WriteLine("一起种树吗");
}
}
class Person
{
static void Main(string[] args)
{
Tree gameObject = new Tree();
Console.ReadKey();
}
}
截图:
父类中的无参构造函数
如果父类中写了有参构造函数,那子类会因找不到父类的无参构造函数而报错,如果你有参和无参都写了,那不会报错。
所以通过base关键字,来调用父类的有参构造函数。
例子:
class GameObject
{
public GameObject()
{
Console.WriteLine("物体位置");
}
}
class Animal : GameObject
{
public Animal(int i)
{
Console.WriteLine("来了{0}只动物", i);
}
}
class Tree : Animal
{
public Tree(int num) : base(num)
{
Console.WriteLine("种了{0}颗树",num);
}
//通过this调用该类参数匹配的构造函数,简接调用了父类
public Tree(int num,string category):this(num)
{
Console.WriteLine("种了{0}颗{1}树", num,category);
}
}
class Person
{
static void Main(string[] args)
{
Tree gameObject = new Tree(5,"草莓");
Console.ReadKey();
}
}
截图:
this与base的区别:
语法上:括号里变量名要与前面构造函数里的参数名一致
this代表该类的某一个构造函数
base代表父类的某一个构造函数