C#中base 关键字的作用

引用:http://msdn.microsoft.com/en-us/library/hfw7t1ce.aspx

base

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

  • 调用基类上已被其他方法重写的方法。

  • 指定创建派生类实例时应调用的基类构造函数。

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

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

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

 1 using System;
 2 using System.Text;
 3 
 4 namespace ConsoleApplication1
 5 {
 6     class Program
 7     {
 8         public class Person
 9         {
10             protected string ssn = "444-55-6666";
11             protected string name = "John L. Malgraine";
12 
13             public virtual void GetInfo()
14             {
15                 Console.WriteLine("Name: {0}", name);
16                 Console.WriteLine("SSN: {0}", ssn);
17             }
18         }
19         class Employee : Person
20         {
21             public string id = "ABC567EFG";
22             public override void GetInfo()
23             {
24                 // Calling the base class GetInfo method:
25                 base.GetInfo();
26                 Console.WriteLine("Employee ID: {0}", id);
27             }
28         }
29 
30         static void Main(string[] args)
31         {
32             Employee E = new Employee();
33             E.GetInfo();
34             Console.ReadKey();
35         }
36     }
37 }

运行结果

说明base作用起到了从派生类中调用基类的方法。注意:在重写基类后调用基类的方法是重写后的方法了

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

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace BaseApplication
 8 {
 9 
10     public class BaseClass
11     {
12         int num = 0;//初始化为0
13         public BaseClass()
14         {
15             Console.WriteLine("in BaseClass()  num=" + num);
16         }
17 
18         public BaseClass(int i)
19         {
20             num = i;
21             Console.WriteLine("in BaseClass(int i)  num={0}", num);
22         }
23 
24         public int GetNum()
25         {
26             return num;
27         }
28     }
29 
30     public class DerivedClass : BaseClass
31     {
32         // 该构造函数将要调用基类不带参数的 BaseClass.BaseClass()
33         public DerivedClass()
34             : base()
35         {
36         }
37 
38         // 该构造函数将要调用基类带参数的 BaseClass.BaseClass(int i)
39         public DerivedClass(int i)
40             : base(i)
41         {
42         }
43     }
44     class Program
45     {
46         static void Main(string[] args)
47         {
48             DerivedClass md = new DerivedClass();
49             DerivedClass md1 = new DerivedClass(1);
50             Console.ReadKey();
51         }
52     }
53 }

运行结果为:

原文地址:https://www.cnblogs.com/abc1069/p/4067215.html