base关键字的说明(学习使用)
2005-12-26 11:05 努力学习的小熊 阅读(1568) 评论(3) 收藏 举报 从本例中大家可以看出继承和重载的使用,各人感觉简明易懂。在第二个例子中大家可以看出如何指定在创建派生类实例时调用的基类构造函数。
base 关键字用于从派生类中访问基类的成员:
- 调用基类上已被其他方法重写的方法。
- 指定创建派生类实例时应调用的基类构造函数。
基类访问只能在构造函数、实例方法或实例属性访问器中进行。
从静态方法中使用 base 关键字是错误的。
示例
在本例中,基类 Person
和派生类 Employee
都有一个名为 Getinfo
的方法。通过使用 base 关键字,可以从派生类中调用基类上的 Getinfo
方法。
1
// keywords_base.cs
2
// Accessing base class members
3
using 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
27
class TestClass {
28
public static void Main()
29
{
30
Employee E = new Employee();
31
E.GetInfo();
32
}
33
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

输出
Name: John L. Malgraine SSN: 444-55-6666 Employee ID: ABC567EFG
示例本示例显示如何指定在创建派生类实例时调用的基类构造函数。
1// keywords_base2.cs
2using System;
3public class MyBase
4{
5int num;
6
7public MyBase()
8{
9Console.WriteLine("in MyBase()");
10}
11
12public MyBase(int i )
13{
14num = i;
15Console.WriteLine("in MyBase(int i)");
16}
17
18public int GetNum()
19{
20return num;
21}
22}
23
24public class MyDerived: MyBase
25{
26// This constructor will call MyBase.MyBase()
27public MyDerived() : base()
28{
29}
30
31// This constructor will call MyBase.MyBase(int i)
32public MyDerived(int i) : base(i)
33{
34}
35
36public static void Main()
37{
38MyDerived md = new MyDerived();
39MyDerived md1 = new MyDerived(1);
40}
41}
输出in MyBase() in MyBase(int i)