| 特性 | 靜態欄位 (static) | 非靜態欄位 (instance) |
|---|---|---|
| 儲存位置 | 高頻堆, 隸屬類別 | 物件實例內部, 隸屬實例 |
| 複製數量 | 整個程式域僅一份 | 每個實例各有一份 |
| 初始化時機 | 類別首次存取前 (靜態建構子) | 每次 new 實例化時 |
| 存取方式 | 類別名.欄位名 | 實例.欄位名 |
| 共享狀態 | 天然共享 | 隔離,需額外機制共享 |
using System;
public class Window {
// 靜態欄位:追蹤所有視窗實例總數
private static int _totalWindows = 0;
public static int TotalWindows => _totalWindows;
// 非靜態欄位:每個視窗獨有的標題與狀態
public string Title { get; set; }
public bool IsActive { get; private set; }
public IntPtr Handle { get; private set; }
// 唯讀實例編號:建構時指派,不可變
public readonly int InstanceId;
public Window(string title) {
Title = title;
InstanceId = ++_totalWindows; // 靜態欄位累加
Handle = CreateWindowHandle(); // 假設建立原生視窗
Console.WriteLine($"Window #{InstanceId} '{Title}' created. Total: {_totalWindows}");
}
~Window() {
_totalWindows--;
DestroyWindowHandle(Handle);
Console.WriteLine($"Window #{InstanceId} destroyed. Total: {_totalWindows}");
}
// 靜態方法:只能存取靜態成員
public static string GetWindowTitle(Window w) => w?.Title ?? "null";
// 非靜態方法:可存取靜態與非靜態成員
public void Activate() {
IsActive = true;
Console.WriteLine($"Window #{InstanceId} activated. Total active: {_totalWindows}");
}
}
Window #1 'Main' created. Total: 1
Window #2 'Settings' created. Total: 2
Window #1 activated. Total active: 2
Window #2 destroyed. Total: 1
Window #1 destroyed. Total: 0
class Demo {
static int _staticField = 10;
int _instanceField = 20;
static void StaticMethod() {
_staticField = 5; // OK
// _instanceField = 5; // CS0120: 需要物件參考
}
void InstanceMethod() {
_staticField = 5; // OK
_instanceField = 5; // OK
}
}
靜態方法無 this 參考,無法知道操作哪個實例的非靜態欄位,因此編譯器禁止直接存取。
ThreadStatic、AsyncLocal 或鎖定/無鎖集合。靜態欄位持有參考型別物件 → 該物件永遠不會被 GC 回收 (除非手動設為 null 或 AppDomain 卸載)。慎用靜態集合儲存大量資料,考慮 WeakReference 或定期清理。