c#訪問this關(guān)鍵字和base關(guān)鍵字示例
指定創(chuàng)建派生類實(shí)例時(shí)應(yīng)調(diào)用的基類構(gòu)造函數(shù);
調(diào)用基類上已被其他方法重寫的方法。
注意:不能從靜態(tài)方法中使用base關(guān)鍵字,base關(guān)鍵字只能在實(shí)例構(gòu)造函數(shù)、實(shí)例方法或?qū)嵗L問器中使用。
例:訪問關(guān)鍵字this和base關(guān)鍵字示例;創(chuàng)建基類Person,包含兩個(gè)數(shù)組成員name和age、一個(gè)具有兩個(gè)參數(shù)的構(gòu)造函數(shù)、一個(gè)虛函數(shù)GetInfo()以顯示數(shù)據(jù)成員name和age的內(nèi)容;創(chuàng)建派生類Student,包含一個(gè)數(shù)據(jù)成員studentId,一個(gè)具有三個(gè)參數(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)鍵字引用類的當(dāng)前實(shí)例
this.age = age; //this 關(guān)鍵字引用類的當(dāng)前實(shí)例
}
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# List 并發(fā)丟數(shù)據(jù)問題原因及解決方案

Unity工具類ScrollView實(shí)現(xiàn)拖拽滑動(dòng)翻頁

在WPF中合并兩個(gè)ObservableCollection集合

C#通過rabbitmq實(shí)現(xiàn)定時(shí)任務(wù)(延時(shí)隊(duì)列)