base 關鍵字用法
阿新 • • 發佈:2021-11-24
base 關鍵字用於從派生類中訪問基類的成員:呼叫基類上已被其他方法重寫的方法。
前半句例項: 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 stringid = "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(); } } 後半句反例: 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); } public virtual void GetInfo1() { Console.WriteLine("Name: {0}-1", name); Console.WriteLine("SSN: {0}-1", ssn); } } class Employee : Person { public stringid = "ABC567EFG"; public override void GetInfo() { // Calling the base class GetInfo method: base.GetInfo1(); //GetInfo1並沒有被重寫 Console.WriteLine("Employee ID: {0}", id); } } class Program { static void Main(string[] args) { Employee E = new Employee(); E.GetInfo(); } }
指定建立派生類例項時應呼叫的基類建構函式。
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); } }
僅允許基類訪問在建構函式、例項方法或例項屬性訪問器中進行。
從靜態方法中使用 base 關鍵字是錯誤的。
所訪問的基類是類宣告中指定的基類