no_self_assignments
不要将变量赋值给自己。
详情
#不要将变量赋值给自己。通常这是一个错误。
错误示例
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
如果您改为使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 no_self_assignments: true
analysis_options.yaml
yaml
linter:
rules:
no_self_assignments: true
除非另有说明,否则本网站上的文档反映的是 Dart 3.7.1 版本。页面上次更新于 2025-03-07。 查看源代码 或 报告问题。