子类继承父类 构造函数访问问题

本文详细解析了C#中构造函数的使用,包括静态构造函数和实例构造函数的调用顺序,以及如何通过base关键字调用基类的带参数构造函数。

using System;
using System.Collections.Generic;
using System.Text;

namespace staticTest
{
    class Program
    {
        static void Main(string[] args)
        {
               parrot parrot1 = new parrot();       
               Console.ReadLine();
        }
       
    }
    class Bird
    {
        static Bird() //静态构造函数前面不允许有访问修饰符
        {
            Console.WriteLine("鸟类的静态构造函数调用了");

        }
        protected Bird()
        {
            Console.WriteLine("一个小鸟被创建了");
        }
     }
    class parrot:Bird
    {
        static parrot()
        {
            Console.WriteLine("鹦鹉的静态构造函数调用了");
        }
        public parrot()
        {
            Console.WriteLine("一个鹦鹉贝创建了");
        }
    }
}

目前的代码执行结果就是:

鹦鹉的静态构造函数调用了
鸟类的静态构造函数调用了
一个小鸟被创建了
一个鹦鹉贝创建了

因为parrot类 继承了Bird 类 所以当调用 parrot 类的构造函数的时候首先要先调用父类的构造函数,调用完以后才调用本类的构造函数,如果父类的构造函数是private 的话就会出错。当创建对象的时候首先要调用类的静态构造函数。

再来看看这个代码

using System;
using System.Collections.Generic;
using System.Text;

namespace staticTest
{
    class Program
    {
        static void Main(string[] args)
        {
            parrot parrot2 = new parrot("傻子", 123);
            Console.ReadLine();
        }
       
    }
    class Bird
    {
        static Bird() //静态构造函数前面不允许有访问修饰符
        {
            Console.WriteLine("鸟类的静态构造函数调用了");

        }
        protected Bird()
        {
            Console.WriteLine("一个小鸟被创建了");
        }
        protected int _weight;
        public Bird(int weight)
        {
            this._weight = weight;
        }
          

    }
    class parrot:Bird
    {
        static parrot()
        {
            Console.WriteLine("鹦鹉的静态构造函数调用了");
        }
        public parrot()
        {
            Console.WriteLine("一个鹦鹉贝创建了");
        }
        private string _name;
        public parrot(string name, int weight)
            : base(weight)
        {
            Console.WriteLine("一只鹦鹉诞生啦名字是{0}体重是{1}",name,weight);
        }
    }
}

这段代码用了带参数的构造函数,当定义了带参数的构造函数的时候 默认的构造函数就失效了 用base()来调用父类的函数,用于对对象的赋值。

转载于:https://www.cnblogs.com/ivy/archive/2008/06/03/1213000.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值