靜態欄位(static)全類別共享單一拷貝;非靜態欄位每實例獨立拷貝。
class Count {
static int Count; // 共享計數
int Number; // 實例編號
public Count() { Count++; Number = Count; }
public void Show() => Console.WriteLine($"Obj{Number}: Count={Count}");
}
Count a = new Count(); a.Show(); // Obj1: Count=1
Count b = new Count(); a.Show(); b.Show(); // Obj1:2, Obj2:2
Count c = new Count(); a.Show(); b.Show(); c.Show(); // 全部 Count=3
Obj1: Count=1 Obj1: Count=2 Obj2: Count=2 Obj1: Count=3 Obj2: Count=3 Obj3: Count=3
Count 所有實例同步更新,證明單一記憶體位置。Number 實例化時刻固定不變,反映建立順序。