base 關鍵字用於從衍生類別中訪問基類的成員:
-
調用基類上已被其他方法重寫的方法。
-
指定建立衍生類別執行個體時應調用的基類建構函式。
基類訪問只能在建構函式、執行個體方法或執行個體屬性訪問器中進行。
從靜態方法中使用 base 關鍵字是錯誤的。
樣本
在本例中,基類 Person 和衍生類別 Employee 都有一個名為 Getinfo 的方法。通過使用 base 關鍵字,可以從衍生類別中調用基類的 Getinfo 方法。
// keywords_base.cs// Accessing base class membersusing System;public class Person{ protected string ssn = "444-55-6666"; protected string name = "John L. Malgraine"; public virtual void GetInfo() { Console.WriteLine("Name: {0}", name); Console.WriteLine("SSN: {0}", ssn); }}class Employee : Person{ public string id = "ABC567EFG"; public override void GetInfo() { // Calling the base class GetInfo method: base.GetInfo(); Console.WriteLine("Employee ID: {0}", id); }}class TestClass{ static void Main() { Employee E = new Employee(); E.GetInfo(); }}
本樣本顯示如何指定在建立衍生類別執行個體時調用的基類建構函式。
// keywords_base2.csusing System;public class BaseClass{ int num; public BaseClass() { Console.WriteLine("in BaseClass()"); } public BaseClass(int i) { num = i; Console.WriteLine("in BaseClass(int i)"); } public int GetNum() { return num; }}public class DerivedClass : BaseClass{ // This constructor will call BaseClass.BaseClass() public DerivedClass() : base() { } // This constructor will call BaseClass.BaseClass(int i) public DerivedClass(int i) : base(i) { } static void Main() { DerivedClass md = new DerivedClass(); DerivedClass md1 = new DerivedClass(1); }}
輸出
Name: John L. MalgraineSSN: 444-55-6666Employee ID: ABC567EFG
有關其他樣本,請參見 new、virtual 和 override。