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

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

问题描述

我正在为 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 是如何改变这些变量的属性的?我试图理解基本概念,因为没有它,我不明白如何或为什么使用 getter 和 setter.

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.

推荐答案

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 = 6; // Won't work since no doors setter is defined
}

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

此外,您还可以在隐式 getter 或 setter 中没有的 getter 或 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;
      }
    }
}

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

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