欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c# base關(guān)鍵字的具體使用

 更新時(shí)間:2024年03月01日 15:53:07   作者:GeGe&YoYo  
base關(guān)鍵字用于從派生類中訪問基類的成員,本文主要介紹了c# base關(guān)鍵字的具體使用,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1. 調(diào)用父類的構(gòu)造函數(shù)

 	class Father
    {
        public int Age { get; set; }
        public string Name { get; set; }
        public Father(int age,string name)
        {
            this.Age = age;
            this.Name = name;
        }
    }
    class Son:Father 
    {
        public int Height { get; set; }
        public Son(int age,string name,int height):base (age,name)
        {
            this.Height = height;
        }
    }

    class grandson : Son
    {
        public grandson(int age, string name, int height) : base(age, name )
        {
            this.Height = height;
        }
    }

會(huì)發(fā)現(xiàn)上面的代碼報(bào)錯(cuò),因?yàn)間randson 這個(gè)類的構(gòu)造函數(shù)使用base調(diào)用父類構(gòu)造函數(shù)時(shí),提示缺少了height這個(gè)參數(shù),這是因?yàn)閎ase調(diào)用的只是它的父類也就是Son這個(gè)類的構(gòu)造函數(shù),而不是最頂層的Father這個(gè)類的構(gòu)造函數(shù),所以這里報(bào)錯(cuò)改成如下代碼即可:

class Father
{
    public int Age { get; set; }
    public string Name { get; set; }
    public Father(int age,string name)
    {
        this.Age = age;
        this.Name = name;
    }
}
class Son:Father 
{
    public int Height { get; set; }
    public Son(int age,string name,int height):base (age,name)
    {
        this.Height = height;
    }
}

class grandson : Son
{
    public grandson(int age, string name, int height) : base(age, name,height  )
    {
        this.Height = height;
    }
}

2. 調(diào)用父類的方法或者屬性

 	class Father
    {
        public int Age { get; set; }
        public string Name { get; set; }
        public Father(int age, string name)
        {
            this.Age = age;
            this.Name = name;
        }
        public void Test()
        {
            Console.WriteLine("我是Father");
        }

    }
    class Son : Father
    {
        public int Height { get; set; }
        public Son(int age, string name, int height) : base(age, name)
        {
            this.Height = height;
        }
        public void Test()
        {
            Console.WriteLine("我是Son");
        }
    }


    class grandson : Son
    {
        public grandson(int age, string name, int height) : base(age, name, height)
        {
            this.Height = height;
        }

        public void Show()
        {
            int age = base.Age;
            base.Test();
        }
    }

調(diào)用:

grandson father = new grandson(100, "小明", 180);
father.Show();

輸出:

我是Son

可以看出調(diào)用的方法不是father類中的test方法,而是Son類,也就是grandson的父類的方法。

到此這篇關(guān)于c# base關(guān)鍵字的具體使用的文章就介紹到這了,更多相關(guān)c# base關(guān)鍵字內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論