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#語言MVC框架Aspose.Cells控件導(dǎo)出Excel表數(shù)據(jù)
這篇文章主要為大家詳細介紹了C#語言MVC框架Aspose.Cells控件導(dǎo)出Excel表數(shù)據(jù),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12
C#獲取當前成員函數(shù)的函數(shù)名的幾種常用方法
本文介紹了在C#中獲取當前成員函數(shù)名稱的幾種方法,包括反射、nameof、CallerMemberName、StackTrace和表達式樹,并給出了最佳實踐推薦,需要的朋友可以參考下2026-02-02
C#開發(fā)WinForm清空DataGridView控件綁定的數(shù)據(jù)
本文詳細講解了C#開發(fā)WinForm清空DataGridView控件綁定數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03

