C#基礎(chǔ)語法:Base關(guān)鍵字學習筆記
它與this關(guān)鍵字一樣,都是作為類的實例(因此不能調(diào)用基類的靜態(tài)成員和抽象成員)簡寫或者替代而存在的,只不過this關(guān)鍵字用于替代本類的實例,base關(guān)鍵字用于替代基類的實例,用法很簡單,其訪問基類的形式如下:
base.【標識符】
base[【表達式列表】] 這個類型的一看便可以大概猜測多用于基類實例的索引器操作,在我下面演示的代碼中你會看到它的用法。
對于 base.【標識符】的訪問形式再次說明一下:
對于非虛方法,這種訪問僅僅是對基類實例成員的直接訪問,完全等價于((base)this).【標識符】。
對于虛方法,對于這種訪子類重寫該虛方法運用這種訪問形式也是(禁用了虛方法調(diào)用的機制)對基類實例成員的直接訪問,將其看做非虛方法處理,此時則不等價于((base)this).【標識符】,因為這種格式完全遵守虛方法調(diào)用的機制,其聲明試時為積累類型,運行時為子類類型,所以執(zhí)行的還是子類的重寫方法。于未重寫的虛方法等同于簡單的非虛方法處理。
測試代碼如下:
using System;
namespace BaseTest
{
class father
{
string str1 = "this field[1] of baseclass", str2 = "this field[2] of baseclass";
public void F1() //Non-virtual method
{
Console.WriteLine(" F1 of the baseclass");
}
public virtual void F2()//virtual method
{
Console.WriteLine(" F2 of the baseclass");
}
public virtual void F3()
{
Console.WriteLine(" F3 of the baseclass that is not overrided ");
}
public string this[int index]
{
set
{
if (index==1 )
{
str1 = value;
}
else
{
str2 = value;
}
}
get
{
if (index ==1)
{
return str1;
}
else
{
return str2;
}
}
}
}
class Child:father
{
public void G()
{
Console.WriteLine("======Non-virtual methods Test =========");
base.F1();
((father)this).F1();
Console.WriteLine("======virtual methods Test=========");
base.F2();
((father)this).F2();
base.F3();
((father)this).F3();
Console.WriteLine("=====Test the type that the tbase [[expression]] ==========");
Console.WriteLine(base[1]);
base[1] = "override the default ";
Console.WriteLine(base[1]);
Console.WriteLine("================Test Over=====================");
}
public override void F2()
{
Console.WriteLine(" F2 of the subclass ");
}
static void Main(string[] args)
{
Child child=new Child();
child.G();
Console.ReadKey();
}
}
}
base用于構(gòu)造函數(shù)聲明,用法和this用于構(gòu)造函數(shù)聲明完全一致,但base是對基類構(gòu)造函數(shù)形參的匹配。
using System;
namespace BaseCoTest
{
class Base
{
public Base(int a, string str)
{
Console.WriteLine("Base. Base(int a,string str)");
}
public Base(int a)
{
Console.WriteLine("Base. Base(int a)");
}
public Base()
{
}
}
class Sub : Base
{
public Sub()
{
}
public Sub(int a)
: base(1, "123")
{
Console.WriteLine("Sub .Sub(int a)");
}
class Test
{
public static void Main()
{
Sub sub = new Sub(1);
Console.ReadKey();
}
}
}
}
相關(guān)文章
解決C# winForm自定義鼠標樣式的兩種實現(xiàn)方法詳解
本篇文章是對在C#中winForm自定義鼠標樣式的兩種實現(xiàn)方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05
C# winform 請求http的實現(xiàn)(get,post)
本文主要介紹了C# winform 請求http的實現(xiàn)(get,post),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06

