no_self_assignments
不要將變數指定給自己。
此規則從 Dart 3.1 開始提供。
詳細資訊
#不要將變數指定給自己。通常這是一個錯誤。
錯誤
dart
class C {
int x;
C(int x) {
x = x;
}
}
正確
dart
class C {
int x;
C(int x) : x = x;
}
正確
dart
class C {
int x;
C(int x) {
this.x = x;
}
}
錯誤
dart
class C {
int _x = 5;
int get x => _x;
set x(int x) {
_x = x;
_customUpdateLogic();
}
void _customUpdateLogic() {
print('updated');
}
void example() {
x = x;
}
}
正確
dart
class C {
int _x = 5;
int get x => _x;
set x(int x) {
_x = x;
_customUpdateLogic();
}
void _customUpdateLogic() {
print('updated');
}
void example() {
_customUpdateLogic();
}
}
錯誤
dart
class C {
int x = 5;
void update(C other) {
this.x = this.x;
}
}
正確
dart
class C {
int x = 5;
void update(C other) {
this.x = other.x;
}
}
用法
#若要啟用 no_self_assignments
規則,請在 analysis_options.yaml
檔案中的 linter > rules 下方新增 no_self_assignments
。
analysis_options.yaml
yaml
linter:
rules:
- no_self_assignments
除非另有說明,否則本網站上的文件反映的是 Dart 3.6.0。頁面最後更新於 2024-07-03。 檢視原始碼或回報問題。