是否可以在DART中的课堂中调用Setter?
是否可以调用DART中使用SET关键字声明的Setter?
在下面编写的脚本中,DART无法识别设置器:
class Cat {
String _size = '';
String _color = '';
int _age = 0;
Cat(String initialSize, String initialColor, int initialAge) {
size(initialSize);
color(initialColor);
age(initialAge);
}
// getter and setter fields are started
String get size {
return _size;
}
void set size(String animalSize) {
_size = animalSize;
}
String get color {
return _color;
}
void set color(String animalColor) {
_color = animalColor;
}
int get age {
return _age;
}
void set age(int animalAge) {
_age = animalAge;
}
// getter and setter fields are ended
}
错误:“大小”不是函数或方法,也无法调用。
错误:“颜色”不是函数或方法,不能调用。
错误:“年龄”不是函数或方法,不能调用。
Is it possible to invoke setters which declaired with set keyword in class in Dart?
In the script written below, Dart does not recognize the setters:
class Cat {
String _size = '';
String _color = '';
int _age = 0;
Cat(String initialSize, String initialColor, int initialAge) {
size(initialSize);
color(initialColor);
age(initialAge);
}
// getter and setter fields are started
String get size {
return _size;
}
void set size(String animalSize) {
_size = animalSize;
}
String get color {
return _color;
}
void set color(String animalColor) {
_color = animalColor;
}
int get age {
return _age;
}
void set age(int animalAge) {
_age = animalAge;
}
// getter and setter fields are ended
}
Error: 'size' isn't a function or method and can't be invoked.
Error: 'color' isn't a function or method and can't be invoked.
Error: 'age' isn't a function or method and can't be invoked.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您调用设置器/Getter的方式是您将如何完成该领域的作业。因此,您的代码应该是:
这将调用
大小
,color
和age
的设置器。拥有Getter/Setter的目的是能够模拟一个字段,但在该字段后面具有一些逻辑,而不是直接访问变量。
与一个问题无关:我不知道您的班级是否只是一个例子,但是您的当前课程可以写如下:
是否要命名参数:
一般不需要它除非您需要具有一些逻辑或要添加限制,否则Getter/setter。 DART中的Getter/Setter的好处是,它们的行为就像字段一样,因此我们可以从字段开始并用Getter和/或Setter替换字段,如果需要添加额外的逻辑。
The way you are calling a setter/getter is how you would do an assignment of the field. So your code should be:
This will call the setter of
size
,color
andage
.The point of having getter/setter is to be able to simulate a field but have some logic behind that field other than just direct access to a variable.
Unrelated to the question: I don't know if your class is just an example but your current class could be written as the following:
Of if you want named parameters:
It is in general not needed to have getter/setters unless you need to have some logic or want to add restrictions. The great thing about getter/setter in Dart is that they behave like fields so we can just start by having fields and replace the field with a getter and/or setter later if we need to add extra logic.