跳到主要內容

instance_member_access_from_static

例項成員不能從靜態方法中訪問。

描述

#

當靜態方法中包含對例項成員的非限定引用時,分析器會產生此診斷資訊。

示例

#

以下程式碼會產生此診斷資訊,因為在靜態方法中引用了例項欄位 x

dart
class C {
  int x = 0;

  static int m() {
    return x;
  }
}

常見修復方法

#

如果該方法必須引用例項成員,則它不能是靜態方法,因此請刪除該關鍵字

dart
class C {
  int x = 0;

  int m() {
    return x;
  }
}

如果該方法不能成為例項方法,則新增一個引數,以便傳入類的例項

dart
class C {
  int x = 0;

  static int m(C c) {
    return c.x;
  }
}