在Dart中,我有这样一个类,它保护getter/setter后面的_x,它允许我控制对_x的更改:
//in a.dart
class A {
int _x;
int get x => _x;
set x(int value) {
bool validation_ok=true;
//do some validation/processing
if (validation_ok) {
_x = value;
//perform side effects that should happen every time _x changes e.g. save to SharedPreferences
print('Validated $value and side effects performed');
}
}
}
//in amain.dart
import 'a.dart';
void main() {
A a = A();
a.x = 5; //if validation successful stores 5 to _x and performs side effects
print(a.x); //prints 'Validated 5 and side effects performed' and then '5'
}但是,如果我想保护一个列表或一个对象而不是int,我能做什么呢?
//in b.dart
class B {
List<int> _y;
List<int> get y => _y;
set y(List<int> value) {
bool validation_ok=true;
//do some validation/processing
if (validation_ok) {
_y = value;
//perform side effects that should happen every time _y changes e.g. save to SharedPreferences
print('Validated $value and side effects performed');
}
}
}
//in bmain.dart
import 'b.dart';
void main() {
B b = B();
b.y = [5]; //if validation successful stores [5] to _y and performs side effects
print(b.y); //prints 'Validated [5] and side effects performed' and '[5]'
b.y.add(6); //now _y is [5,6] but no validation was done on 6 and no side effects performed
print(b.y); //prints '[5,6]' only
}注意,在bmain.dart中,行b.y.add(6)添加到私有列表中,而不需要遍历setter。如何确保不允许此类访问,并控制对私有列表或对象的任何更改?
发布于 2019-11-12 07:59:41
您不能公开一个可变的对象,并确保它不会被其他人更改。剩下的选择如下:
前者并没有听上去那么糟糕。如果给容器类成员访问受保护对象的成员,则不必公开对象本身。(这甚至可能是个好主意,q.v。“德米特定律”)。
后者意味着将真正的对象包装在视图适配器中,如果您想要进行更改,该适配器将抛出。对于List,可以使用UnmodifiableListView。对于其他类,您可能需要自己编写一个类。这个解决方案显然只是肤浅。访问不可修改列表的代码不能更改哪些对象是列表的元素,但是如果这些对象本身是可变的,那么它们也可以更改。通常,保护列表本身就是你所需要的。
https://stackoverflow.com/questions/58809081
复制相似问题