getters和setter如何改变Dart中的属性? [英] How do getters and setters change properties in Dart?

查看:1095
本文介绍了getters和setter如何改变Dart中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Dart中遇到了getter和setter的概念,而且我读的越多,我就越不能掌握底层的目的。例如下面的代码:

I am struggling with the concept of getters and setters in Dart, and the more I read, the more I cannot grasp the underlying purpose. Take for example the following code:

main() {
    Car car = new Car();
    car.doors = 44;
    print(car.doors);  // 44
}
class Car {
    int doors = 4;
}

后来,我决定把门变成一个私有变量,

Later, I decide to make "doors" a private variable, so I do the following:

main() {
    Car car = new Car();
    car.doors = 44;
    print(car.doors);  // 44
}
class Car {
    int _doors = 4;
    int get doors => _doors;
    set doors(int numberOfDoors) => _doors = numberOfDoors;
}

根据代码, _doors 现在是一个私有变量,所以我不能访问它在main()。然而,通过操作 doors ,我可以间接改变 _doors 的值,这是我想要防止首先使它成为一个私有变量。那么,将先前的公共变量变成私有变量的目的是什么,如果你仍然可以间接操作它?并且,getter和setter如何工作来改变这些变量的属性?我试图理解的基本概念,因为没有这个,我不明白如何或为什么getters和setters被使用。

According to the code, _doors is now a private variable, and so I cannot access it in main(). However, by manipulating doors, I can indirectly change the value of _doors, which is what I thought I wanted to prevent in the first place by making it a private variable. So what is the purpose of making a previously public variable into a private one, if you can still indirectly manipulate it? And, how are getters and setters even working to change the properties of these variables? I am trying to understand the fundamental concept, because without that, I don't understand how or why getters and setters are used.

推荐答案

p> Dart中的实例变量具有隐式getter和setter。所以对于你的示例代码,它将以完全相同的方式操作,因为你所做的一切都从一个隐式的getter和setter改为一个显式的getter和setter。

Instance variables in Dart have implicit getters and setters. So for your example code, it will operate in exactly the same way, since all you have done is changed from an implicit getter and setter to an explicit getter and setter.

显式getter和setter的值是你不需要定义两者,如果你不想要。例如我们可以改变你的例子只定义一个getter:

The value of explicit getters and setters is that you don't need to define both if you don't want. For instance we can change your example to only define a getter:

main() {
    Car car = new Car();
    print(car.doors);  // 4
    car.doors = 44; // Won't work since no doors setter is defined
}

class Car {
    int _doors = 4;
    int get doors => _doors;
}

此外,您还可以在getter或setter中添加额外的逻辑'get in a implicit getter or setter:

Additionally, you can also add extra logic in a getter or setter that you don't get in an implicit getter or setter:

class Car {
    int _doors = 4;
    int get doors => _doors;
    set doors(int numberOfDoors) {
      if(numberOfDoors >= 2 && numberOfDoors <= 6) {
        _doors = numberOfDoors;
      }
    }
}

这篇关于getters和setter如何改变Dart中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆