c#訪問this關(guān)鍵字和base關(guān)鍵字示例
指定創(chuàng)建派生類實例時應調(diào)用的基類構(gòu)造函數(shù);
調(diào)用基類上已被其他方法重寫的方法。
注意:不能從靜態(tài)方法中使用base關(guān)鍵字,base關(guān)鍵字只能在實例構(gòu)造函數(shù)、實例方法或?qū)嵗L問器中使用。
例:訪問關(guān)鍵字this和base關(guān)鍵字示例;創(chuàng)建基類Person,包含兩個數(shù)組成員name和age、一個具有兩個參數(shù)的構(gòu)造函數(shù)、一個虛函數(shù)GetInfo()以顯示數(shù)據(jù)成員name和age的內(nèi)容;創(chuàng)建派生類Student,包含一個數(shù)據(jù)成員studentId,一個具有三個參數(shù)的派生類構(gòu)造函數(shù),并用:base調(diào)用基類構(gòu)造函數(shù)、并重寫所繼承基類的虛方法GetInfo(),調(diào)用基類的方法顯示name和age的內(nèi)容。
namespace ConsoleApplication
{
public class Person //基類、等同于public class Person:Object
{
public string name;
public uint age;
public Person(string name,uint age)//基類的構(gòu)造函數(shù)
{
this.name = name; //this 關(guān)鍵字引用類的當前實例
this.age = age; //this 關(guān)鍵字引用類的當前實例
}
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}",name);
Console.WriteLine("Age:{0}",age);
}
}
public class Student:Person//派生類
{
public string studentId;
//派生類構(gòu)造函數(shù)并用:base調(diào)用基類構(gòu)造函數(shù)
public Student(string name,uint age,string studentId):base(name,age)
{
this.studentId = studentId;
}
public override void GetInfo()
{
//調(diào)用基類方法
base.GetInfo();
Console.WriteLine("StudentId: {0}",studentId);
}
}
public class Program
{
static void Main(string[] args)
{
Student objstudent=new Student("jeamsluu",99,"20140101011");
objstudent.GetInfo();
Console.ReadKey();
}
}
}
相關(guān)文章
C#實現(xiàn)高效查找替換Excel表格數(shù)據(jù)或文本
在現(xiàn)代數(shù)據(jù)驅(qū)動的業(yè)務環(huán)境中,Excel表格扮演著不可或缺的角色,本文將深入探討如何利用C#編程語言,精準地實現(xiàn)Excel表格中的數(shù)據(jù)和文本查找與替換,感興趣的小伙伴可以了解下2025-09-09
C#統(tǒng)計字符串中數(shù)字個數(shù)的方法
這篇文章主要介紹了C#統(tǒng)計字符串中數(shù)字個數(shù)的方法,涉及C#遍歷字符串并判斷數(shù)字的技巧,需要的朋友可以參考下2015-06-06
WPF/Silverlight實現(xiàn)圖片局部放大的方法分析
這篇文章主要介紹了WPF/Silverlight實現(xiàn)圖片局部放大的方法,結(jié)合實例形式分析了WPF/Silverlight針對圖片屬性操作相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2017-03-03
C#基礎(chǔ)教程之IComparable用法,實現(xiàn)List<T>.sort()排序
這篇文章主要介紹了C#的一些基礎(chǔ)知識,主要是IComparable用法,實現(xiàn)List<T>.sort()排序,非常的實用,這里推薦給大家。2015-02-02

