靜態方法(static)屬於類別,無 this**;非靜態方法屬於實例,可存取所有成員。
class A {
int x; static int y;
static int F() { /*x=1;*/ y=2; } // ❌ 靜態方法不可存取非靜態 x
}
原因:x 每實例一份,靜態方法無 this 無法知道存取哪個實例的 x。
class Window {
public string Caption; public bool IsActive; public IntPtr Handle;
public static int TotalOpen;
public Window() { TotalOpen++; /*建立視窗*/ Handle = ...; }
~Window() { TotalOpen--; /*銷毀視窗*/ }
public static string GetCaption(Window w) => w.Caption; // 透過參數存取實例成員
}
靜態方法 GetCaption 接收 Window 參數,即可存取該實例的非靜態成員。
static。