在 C# 類中,靜態方法 (如 `static void Main()` 或其他 `static` 方法) 直接調用同類的**非靜態 (實例) 方法**,編輯器顯示紅色波浪線,提示:「無法通過類型「ClassName」訪問非靜態成員「MethodName」」。
class Program {
// 非靜態方法 (實例方法)
public void Print() {
Console.WriteLine("Hello Instance");
}
static void Main(string[] args) {
Print(); // ❌ 錯誤:靜態上下文無法直接調用實例方法
// Program.Print(); // 同樣錯誤
}
}
static void Main(string[] args) {
Program p = new Program(); // 創建實例
p.Print(); // 通過實例調用 ✅
}
// 若 Print() 不使用任何非靜態字段/屬性
public static void Print() { // 加 static
Console.WriteLine("Hello Static");
}
static void Main(string[] args) {
Print(); // ✅ 直接調用靜態方法
// 或 Program.Print();
}
public void AnotherMethod() {
this.Print(); // ✅ 實例方法中隱式有 this,可直接調用
Print(); // ✅ 省略 this 也可
}
若截圖中 `Main` 是靜態的,`Print` 是非靜態的:
static void Main(string[] args) {
// 原代碼: Print(); // 波浪線
// 修正:
new Program().Print(); // 一行創建並調用
// 或
Program p = new Program();
p.Print();
}
| 特性 | 靜態成員 (static) | 實例成員 (非 static) |
|---|---|---|
| 歸屬 | 類 | 對象 (實例) |
| 調用語法 | `ClassName.StaticMember()` | `instance.InstanceMember()` |
| this 可用性 | ❌ 無 this | ✅ 隱式 this |
| 訪問靜態成員 | ✅ 直接訪問 | ✅ 可訪問 (推薦類名.調用) |
| 訪問實例成員 | ❌ 必須通過實例 | ✅ 直接訪問 |
| 生命周期 | 程序啟動到結束 | 對象創建到 GC 回收 |
紅波浪線提示「無法通過類型訪問非靜態成員」,核心是**靜態上下文缺少實例引用**。修正核心:**`new ClassName().Method()` 創建實例調用**,或**將方法標記為 `static`** (若邏輯允許)。新手必須牢記:`static` = 類級,無 `this`;非 `static` = 實例級,需 `this`。