c# base關(guān)鍵字的具體使用
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; } }
會發(fā)現(xiàn)上面的代碼報錯,因為grandson 這個類的構(gòu)造函數(shù)使用base調(diào)用父類構(gòu)造函數(shù)時,提示缺少了height這個參數(shù),這是因為base調(diào)用的只是它的父類也就是Son這個類的構(gòu)造函數(shù),而不是最頂層的Father這個類的構(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,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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#中調(diào)用Windows API的技術(shù)要點說明
本篇文章主要是對C#中調(diào)用Windows API的技術(shù)要點進行了詳細的介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01C#使用Winform連接SQL Server數(shù)據(jù)庫的詳細步驟
Windows Forms是一個用于構(gòu)建Windows桌面應(yīng)用程序的圖形用戶界面(GUI)庫,它是.NET Framework的一部分,允許開發(fā)者快速創(chuàng)建豐富的交互式界面,本文給大家介紹了C#使用Winforms連接SQL Server數(shù)據(jù)庫的詳細步驟,需要的朋友可以參考下2024-09-09C#實現(xiàn)JSON和對象之間互相轉(zhuǎn)換功能示例
這篇文章主要介紹了C#實現(xiàn)JSON和對象之間互相轉(zhuǎn)換功能,結(jié)合實例形式較為詳細的分析了C#實現(xiàn)對象與json之間相互轉(zhuǎn)換的操作技巧,需要的朋友可以參考下2017-09-09C# OpenCvSharp實現(xiàn)去除字母后面的雜線
這篇文章主要為大家詳細介紹了C#如何使用OpenCvSharp實現(xiàn)去除字母后面的雜線效果,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習一下2023-11-11c# 數(shù)據(jù)標注與數(shù)據(jù)校驗
這篇文章主要介紹了c# 數(shù)據(jù)標注與數(shù)據(jù)校驗的相關(guān)資料,幫助大家更好的理解和學(xué)習c#,感興趣的朋友可以了解下2020-10-10