c#基础-继承-12.继承中的构造函数

特点:在子类对象实例化时,默认会先调用父类的构造函数,一直往上找父亲。从老祖宗开始执行,一代一代往下。

例子:

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代表父类的某一个构造函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值