代码改变世界

base关键字的说明(学习使用)

2005-12-26 11:05  努力学习的小熊  阅读(1528)  评论(3编辑  收藏  举报

        从本例中大家可以看出继承和重载的使用,各人感觉简明易懂。在第二个例子中大家可以看出如何指定在创建派生类实例时调用的基类构造函数。

base
关键字用于从派生类中访问基类的成员:

  • 调用基类上已被其他方法重写的方法。
  • 指定创建派生类实例时应调用的基类构造函数。

基类访问只能在构造函数、实例方法或实例属性访问器中进行。

从静态方法中使用 base 关键字是错误的。

示例
        在本例中,基类 Person 和派生类 Employee 都有一个名为 Getinfo 的方法。通过使用 base 关键字,可以从派生类中调用基类上的 Getinfo 方法。

 1// keywords_base.cs
 2// Accessing base class members
 3using System;
 4   public class Person 
 5   {
 6      protected string ssn = "444-55-6666";
 7      protected string name = "John L. Malgraine";
 8
 9      public virtual void GetInfo() 
10      {
11         Console.WriteLine("Name: {0}", name);
12         Console.WriteLine("SSN: {0}", ssn);
13      }

14   }

15   class Employee: Person 
16   {
17      public string id = "ABC567EFG";
18
19      public override void GetInfo() 
20      {
21         // Calling the base class GetInfo method:
22         base.GetInfo();
23         Console.WriteLine("Employee ID: {0}", id);
24      }

25   }

26
27class TestClass {
28   public static void Main() 
29   {
30      Employee E = new Employee();
31      E.GetInfo();
32   }

33}

输出

Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG












示例

    本示例显示如何指定在创建派生类实例时调用的基类构造函数。

 1// keywords_base2.cs
 2using System;
 3public class MyBase
 4{
 5   int num;
 6
 7   public MyBase() 
 8   {
 9      Console.WriteLine("in MyBase()");
10   }

11
12   public MyBase(int i )
13   {
14      num = i;
15      Console.WriteLine("in MyBase(int i)");
16   }

17
18   public int GetNum()
19   {
20      return num;
21   }

22}

23
24public class MyDerived: MyBase
25{
26   // This constructor will call MyBase.MyBase()
27   public MyDerived() : base()
28   {
29   }

30
31    // This constructor will call MyBase.MyBase(int i)
32   public MyDerived(int i) : base(i)
33   {
34   }

35
36   public static void Main() 
37   {
38      MyDerived md = new MyDerived();
39      MyDerived md1 = new MyDerived(1);
40   }

41}


输出

in MyBase()
in MyBase(int i)