類別由欄位(狀態)與成員(行為)構成。欄位建議設為 private/protected,透過屬性提供受控存取。
public class Car {
// 私有欄位
private int _speed;
private string _name;
// 屬性封裝
public int Speed {
set { _speed = value; }
get { return _speed; }
}
public string Name {
set { _name = value; }
get { return _name; }
}
// 預設建構子
public Car() { }
// 多載建構子
public Car(string name, int speed) {
_name = name;
_speed = speed;
}
// 方法
public void ShowState() {
Console.WriteLine("Car {0} is going {1} MPH", _name, _speed);
}
}
new 在堆疊配置記憶體,否則編譯錯誤(Car c; c.Name = "X"; // CS0165)。Car c = new Car("Bruce", 150);
c.ShowState();
| 類型 | 特徵 | 用途 |
|---|---|---|
| 預設建構子 | 無參數,編譯器自動提供(除非自訂建構子) | 將欄位初始化為預設值(0/null/false) |
| 自訂建構子 | 可帶參數,執行自訂初始化邏輯 | 建立物件時直接設定狀態 |
| 靜態建構子 | static ClassName(),無修飾詞、無參數、每類別僅執行一次 | 初始化靜態欄位、執行一次性設定 |
注意:定義任何自訂建構子後,預設建構子會被移除,若仍需無參數建構子必須顯式宣告。
this._name = name; 區分欄位與參數。this(...) 呼叫。
public Car() : this(0, "") { }
public Car(int speed) : this(speed, "") { }
public Car(string name) : this(0, name) { }
// 主建構子
public Car(int speed, string name) {
if (speed > 150) speed = 150;
this.Speed = speed;
this.Name = name;
}
SomeMethod(this) 或回傳 this 實現流暢介面。讓類別實例像陣列一樣用 [index] 存取元素:
public class CarCollection : IEnumerable {
private ArrayList _cars = new ArrayList();
public Car this[int index] {
get { return (Car)_cars[index]; }
set { _cars.Insert(index, value); }
}
// 實作 IEnumerable...
}
ClassName.Member 存取。static class Program {
static void Main(string[] args) { /* 入口點 */ }
}
精通類別結構、建構子鏈結、索引子與靜態成員,是寫出清晰、可維護 C# 程式碼的基石。善用 this 消除模糊、集中驗證邏輯,能大幅減少重複程式碼與潛在 Bug。