创建子类对像时候 默认调用父类的无参数的构造函数,不会调用带参数构造函数
创建子类对象的时候可以调用父类的带参数的构造函数,在子类的构造函数后面:base()调用父类的构造
动物类 父类
class Animal
{
public string Name { get; set; }
public char Sex;
public Animal()
{
Console.WriteLine("我是Animal的五参数的构造函数");
}
public Animal(string n1, char s1)
{
Name = n1;
Sex = s1;
Console.WriteLine("我是Animal的有参数的构造函数");
}
}
小狗类 子类
class Dog :Animal
{
public Dog()
{
Console.WriteLine("我是Dog的无参数的构造函数");
}
// :base()基础类,父类, :base()调用父类的构造函数,父类又是带参数的构造函数,所以base传递两个参数
// base(n1,'男')两个参数分别是(藏獒,'男')
public Dog(string n1):base(n1,'男')
{
Console.WriteLine("我是Dog类的带参数的构造函数");
}
}
Main
Dog jinmao = new Dog();
Console.WriteLine(jinmao.Name +"," +jinmao.Sex);
Dog zangao = new Dog("藏獒");
Console.WriteLine(zangao.Name +","+zangao.Sex);