我曾经在Kotlin编程很长时间了。我在Dart编程中很新。
因此,我想知道Dart编程中是否需要getter和setter。(如果getter和setter没有逻辑,则为纯getter,setter)
我的IDE是VSCode。当我尝试查看设置了特定变量的位置并获取=>时,我使用了“查找所有引用”。此功能显示设置和获取的混合。因此,我认真考虑将每个字段设置为setter和getter。
当我使用Kotlin时,该语言会自动生成getter和setter。IDE为我提供了get / set的单独参考。对我来说,使每个吸气剂塞特器很烦人。
用IDE查看设置/获取的单独引用的任何好方法吗?还是有其他原因使用getter和setter?(如果getter和setter没有逻辑,则为纯getter,setter)
class DisplayConstant {
double statusbarHeight = 0;
double devicePixelRatio = 1;
}
Run Code Online (Sandbox Code Playgroud)
与
class DisplayConstant {
double _statusbarHeight = 0;
double _devicePixelRatio = 1;
double get statusbarHeight => _statusbarHeight;
set statusbarHeight(double statusbarHeight) =>
_statusbarHeight = statusbarHeight;
double get devicePixelRatio => _devicePixelRatio;
set devicePixelRatio(double devicePixelRatio) =>
_devicePixelRatio = devicePixelRatio;
}
Run Code Online (Sandbox Code Playgroud)
使用getter / setter是可选的。在某些情况下,例如在获取数据时需要添加其他逻辑的情况下,这可能会有所帮助。
class DisplayConstant {
//make your variables private using _ at the beginning
double _factor = 0.5;
double _statusbarHeight = 0;
double _devicePixelRatio = 1;
double get statusbarHeight => _statusbarHeight * _factor;
double get devicePixelRatio => _devicePixelRatio * _factor;
set statusbarHeight(double statusbarHeight) => _statusbarHeight = statusbarHeight;
set devicePixelRatio(double devicePixelRatio) =>_devicePixelRatio = devicePixelRatio;
}
Run Code Online (Sandbox Code Playgroud)
使用setter和getter对类的用户透明。这样一来,您就可以随着时间的推移不断发展自己的API,而不会破坏现有的用户,如下所示:
final display = DisplayConstant();
//set your data
display.statusbarHeight = 20;
display.devicePixelRatio = 0.5;
//get your data
print(display.statusbarHeight);
print(display.devicePixelRatio);
Run Code Online (Sandbox Code Playgroud)
如果您不打算在获取属性时计划添加一些逻辑,则可以避免获取/设置并直接调用属性。
您可以在此链接中找到更多信息:http : //dartdoc.takyam.com/dart-tips/dart-tips-ep-10.html
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |