我有MyDateTime
类,它有一个变量hour
。创建对象时,我需要在某种条件下设置此变量。例如,我有这个对象:MyDateTime dt = MyDateTime(2020, 2, 3, 3, 2);
现在我需要增加hour
,即dt.hour++;
我的问题是如何在不添加新功能的情况下更改对象的hour
,同时我需要增加hour
的条件
class MyDateTime {
int year;
int month;
int day;
int hour;
int minute;
int second;
MyDateTime({this.year, this.month, this.day ,this.hour=0, this.minute=0, this.second=0});
// this is the condition
set addHour(int h){
if(this.hour == 23) this.hour = 0;
else if(this.hour == 0) this.hour = 1;
else this.hour++;
}
}
我不想具有功能(例如:
addHour
)有办法吗?
最佳答案
您可以为此使用自定义 setter :
class MyDateTime {
int year;
int month;
int day;
int _hour;
int minute;
int second;
MyDateTime({this.year, this.month, this.day, int hour=0, this.minute=0, this.second=0}) : _hour = hour;
// this is the condition
set hour(int h) => _hour = h % 24;
// We need to define a custom getter as well.
int get hour => _hour;
}
然后,您可以执行以下操作:
main() {
final dt = MyDateTime();
print(dt.hour); // 0
print(++dt.hour); // 1
dt.hour += 2;
print(dt.hour); // 3
}
关于flutter - 用 Dart 条件设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60060305/