1、base 关键字用于从派生类中访问基类的成员:
(1) 调用基类上已被其他方法重写的方法,如base实例1; (2) 指定创建派生类实例时应调用的基类构造函数,如base实例2。 基类访问只能在构造函数、实例方法或实例属性访问器中进行。 base实例1
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace BaseTest1 7 { 8 class Animal 9 { 10 public virtual void Display() 11 { 12 Console.WriteLine("The base animal class is Animal"); 13 } 14 } 15 class Monkey : Animal 16 { 17 public override void Display() 18 { 19 base.Display(); 20 Console.WriteLine("The monkey class is Monkey"); 21 } 22 } 23 class Program 24 { 25 static void Main(string[] args) 26 { 27 Monkey monkey = new Monkey(); 28 monkey.Display(); 29 } 30 } 31 }
base实例2
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace BaseTest 7 { 8 class Animal 9 { 10 public Animal() 11 { 12 Console.WriteLine("in Animal()"); 13 } 14 public Animal(int newanimal) 15 { 16 int num = newanimal; 17 Console.WriteLine("in Animal(int {0})",num); 18 } 19 } 20 class Monkey : Animal 21 { 22 public Monkey() 23 : base() 24 { 25 Console.WriteLine("in Monkey()"); 26 } 27 public Monkey(int newanimal) 28 : base(newanimal) 29 { 30 31 } 32 } 33 class Program 34 { 35 static void Main(string[] args) 36 { 37 Monkey monkey = new Monkey(); 38 Monkey monkey1 = new Monkey(10); 39 } 40 } 41 }
2、this关键字引用类的当前实例,如this综合实例。
以下是 this 的常用用途:
- 限定被相似的名称隐藏的成员
- 将对象作为参数传递到其他方法
- 声明索引器
this综合实例
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ThisTest 7 { 8 class Employee 9 { 10 private string _name; 11 private int _age; 12 private string[] _arr = new string[5]; 13 14 public Employee(string name, int age) 15 { 16 //使用this限定字段,name与age 17 this._name = name; 18 this._age = age; 19 } 20 21 public string Name 22 { 23 get { return this._name; } 24 } 25 26 public int Age 27 { 28 get { return this._age; } 29 } 30 31 // 打印雇员资料 32 public void PrintEmployee() 33 { 34 // 将Employee对象作为参数传递到DoPrint方法 35 Print.DoPrint(this); 36 } 37 38 // 声明索引器 39 public string this[int param] 40 { 41 get { return _arr[param]; } 42 set { _arr[param] = value; } 43 } 44 45 } 46 class Print 47 { 48 public static void DoPrint(Employee e) 49 { 50 Console.WriteLine("Name: {0}\nAge: {1}", e.Name, e.Age); 51 } 52 } 53 class Program 54 { 55 static void Main(string[] args) 56 { 57 Employee E = new Employee("Huang", 28); 58 E[0] = "Sky"; 59 E[1] = "Emily"; 60 E[4] = "Karen"; 61 E.PrintEmployee(); 62 63 for(int i=0; i<5; i++) 64 { 65 Console.WriteLine("Friends Name: {0}", E[i]); 66 } 67 68 } 69 } 70 }
此实例参考: