1.base关键字用于从派生类中访问基类的成员:
(1)调用基类上已被其他方法重写的方法
(2)指定创建派生类实例时应调用的基类构造函数
2.基类访问只能在构造函数、实例方法或实例属性访问器中进行
3.从静态方法中使用base关键字是错误的。
4.在本例中,基类Person和派生类Employee都有一个名为Getinfo的方法。通过使用base关键字,可以从派生类中调用基类的Getinfo方法
// keywords_base.cs // Accessing base class members using 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(); } }
输出:
Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG
5.本例显示如何制定在创建派生类实例时调用的基类构造函数
// keywords_base.cs // Accessing base class members using 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(); } }
输出:
in BaseClass() in BaseClass(int i)
时间: 2024-11-26 18:48:59