它與this關鍵字一樣,都是作為類的實例(因此不能調用基類的靜態成員和抽象成員)簡寫或者替代而存在的,只不過this關鍵字用于替代本類的實例,base關鍵字用于替代基類的實例,用法很簡單,其訪問基類的形式如下:
base.【標識符】
base[【表達式列表】] 這個類型的一看便可以大概猜測多用于基類實例的索引器操作,在我下面演示的代碼中你會看到它的用法。
對于 base.【標識符】的訪問形式再次說明一下:
對于非虛方法,這種訪問僅僅是對基類實例成員的直接訪問,完全等價于((base)this).【標識符】。
對于虛方法,對于這種訪子類重寫該虛方法運用這種訪問形式也是(禁用了虛方法調用的機制)對基類實例成員的直接訪問,將其看做非虛方法處理,此時則不等價于((base)this).【標識符】,因為這種格式完全遵守虛方法調用的機制,其聲明試時為積累類型,運行時為子類類型,所以執行的還是子類的重寫方法。于未重寫的虛方法等同于簡單的非虛方法處理。
測試代碼如下:
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用于構造函數聲明,用法和this用于構造函數聲明完全一致,但base是對基類構造函數形參的匹配。
 
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();      }    }  }}新聞熱點
疑難解答