類別是建立物件的樣板,定義每個實例包含的資料與功能。
public class Doctor {
public Doctor() {}
public Doctor(string name, byte age) {
this._name = name;
this._age = age;
}
private string _name;
private byte _age;
public string Name {
get { return this._name; }
set { this._name = value; }
}
public byte Age {
get { return this._age; }
set { this._age = value; }
}
public string DoSth() { return "我會給人治病喔~~"; }
public static string DoAnth() { return "執行的另一個靜態方法"; }
}
public class OneDoctor {
static void Main() {
Doctor dc = new Doctor();
dc.Name = "李四"; dc.Age = 25;
Doctor dc2 = new Doctor("張三", 35);
Console.WriteLine(dc.Name); // 李四
Console.WriteLine(dc.Age); // 25
Console.WriteLine(dc2.Name); // 張三
Console.WriteLine(dc2.Age); // 35
Console.WriteLine(dc.DoSth());
Console.WriteLine(Doctor.DoAnth());
}
}
Doctor()、Doctor(string,byte) 為多載建構子。get/set 封裝私有欄位,取代 Java 的 getter/setter。DoAnth() 透過類別名直接呼叫,無需實例化。