this和base
C#的this關鍵字表示當前類的當前實例,this關鍵字通常用於把類的當前實例作為參數傳遞給別的方法。由於this表示一個類的實例,所以在類的靜態成員中,不能使用this關鍵字。
public class Student { public Student(string n, string s, int a, int g) { name = n; sex = s; age = a; grade = g; } private string _name; public string name { get { return _name; } set { _name = value; } } private string _sex; public string sex { get { return _sex; } set { _sex = value; } } private int _age; public int age { get { return _age; } set { _age = value; } } private int _grade; public int grade { get { return _grade; } set { _grade = value; } } public bool joinCommunity(StudentCommunity sc) { return sc.addMember(this); } } public class StudentCommunity { private const int MaxStudents = 100; private Student[] members = new Student[MaxStudents]; private string _name; public string name { get { return _name; } set { _name = value; } } private int _count = 0; public int count { get { return _count; } } public bool addMember(Student s) { if (count < MaxStudents) { members[count] = s; _count++; return true; } else { return false; } } public void displayMembers() { for (int i = 0; i < count; i++) { Student s = members[i]; Console.WriteLine("成員[{0}]\t姓名:{1}\t性別:{2}\t年齡:{3}\t年級:{4}", i + 1, s.name, s.sex, s.age, s.grade); } } } static void Main(string[] args) { StudentCommunity community = new StudentCommunity(); community.name = "Basketball Community"; Student student = new Student("Nick", "Male", 25, 3); student.joinCommunity(community); student = new Student("Jason", "Male", 26, 4); student.joinCommunity(community); student = new Student("Jessice", "Female", 23, 2); student.joinCommunity(community); community.displayMembers(); Console.ReadLine(); }
運行結果
成員[1] 姓名:Nick 性別:Male 年齡:25 年級:3 成員[2] 姓名:Jason 性別:Male 年齡:26 年級:4 成員[3] 姓名:Jessice 性別:Female 年齡:23 年級:2
base關鍵字表示當前類的基類。可以用base關鍵字調用基類的方法、屬性和成員變量。如下代碼所示:
public class Mammal { public Mammal() { age = 0; } public Mammal(int a) { age = a; } private int _age; public int age { get { return _age; } set { _age = value; } } public void bark() { Console.WriteLine("Mammal bark!"); } } public class Dog:Mammal { public void bark() { base.bark();//調用基類方法 Console.WriteLine("Dog bark!"); } } static void Main(string[] args) { Dog dog = new Dog(); dog.bark(); Console.ReadLine(); }
運行結果
Mammal bark! Dog bark!
構造函數相互調用
在編寫類代碼時會遇到一種特殊的函數調用關系,就是構造函數之間的相互調用。構造函數相互調用分為同一個類的各個不同構造函數之間的調用和派生類調用基類的構造函數,前者使用this關鍵字,後者使用base關鍵字。
public class Dog:Mammal { public Dog(int a, string n) :base(a) //調用基類構造函數 { name = n; } public Dog() :this(0, "HaHa") //調用相同類的另外一個構造函數 { //// } public void bark() { base.bark();//調用基類方法 Console.WriteLine("Dog bark!"); } private string _name; public string name { get { return _name; } set { _name = value; } } }