base与this
1、base 關(guān)鍵字用于從派生類中訪問基類的成員: ??
? ? (1) 調(diào)用基類上已被其他方法重寫的方法,如base實(shí)例1; ?
? ? (2) 指定創(chuàng)建派生類實(shí)例時(shí)應(yīng)調(diào)用的基類構(gòu)造函數(shù),如base實(shí)例2。 ??
基類訪問只能在構(gòu)造函數(shù)、實(shí)例方法或?qū)嵗龑傩栽L問器中進(jìn)行。
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實(shí)例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關(guān)鍵字引用類的當(dāng)前實(shí)例,如this綜合實(shí)例。
以下是?this?的常用用途:
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對象作為參數(shù)傳遞到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 }
此實(shí)例參考:http://www.cnblogs.com/hunts/archive/2007/01/11/618158.html
?
總結(jié)
- 上一篇: Kobject
- 下一篇: C#温故而知新学习系列之XML编程—Xm