.Net (C#)Base关键字的使用

    技术2025-08-06  16

    Base关键字可以完成创建派生类实例时调用其基类的构造函数或者调用基类上已被其他方法重写的方法。

     

    1.Base调用基类的构造函数

     

            private void button1_Click(object sender, EventArgs e)        {            Example_1_ ea = new Example_1_();     //实例化Examp_1_了类        }

     

     

        class Example      //基类    {        public Example()        {            MessageBox.Show("执行构造函数Example");        }    }

     

     

        class Example_1_:Example    //派生类    {        public Example_1_()      //派生类的构造函数            : base()        {            MessageBox.Show("调用了Example【1】");        }    }

     

    运行结果:执行了构造函数Example

                   调用了Example【1】

     

    2.Base在派生类中调用基类的方法

     

            private void button1_Click(object sender, EventArgs e)        {            Example_1_ ea = new Example_1_();    //实例化派生类            ea.GetMake();    //调用GetMake方法        }

     

        class Example    {        public void DispInfo()        {            MessageBox.Show("调用了基类中的DispInfo方法");        }    }

     

     

        class Example_1_:Example    {        public void GetMake()        {            base.DispInfo();     调用基类中的DispInfo方法            MessageBox.Show("执行了派生类中的GetMake");        }    }

     

     

    运行结果:调用了基类中的DispInfo方法

                   执行了派生类中的GetMake

    最新回复(0)