gpt4 book ai didi

flutter - 在 Dart 中将 Setter 与构造函数一起使用

转载 作者:行者123 更新时间:2023-12-02 19:13:26 25 4
gpt4 key购买 nike

如何在 Dart 的默认构造函数中使用私有(private)实例变量的 setter?

给定示例类:

class A {
String name;
int _age;

int get age => _age;

set age(age) {
_age = age ?? 0;
}

A(this.name, this._age);
}

如何使用这个构造函数来遍历 set age() 函数?除了使用 factory 之外还有其他方法吗?我想做这样的事情

A(this.name, newAge): age = newAge;

但是我收到一个错误,迫使我只能从构造函数中设置实例变量,这让我只是复制了 setter:

A(this.name, newAge): _age = newAge ?? 0;

我是不是遗漏了什么,或者这对 dart 来说是不可能的吗?

最佳答案

构造函数的初始化列表只能用于初始化成员(或调用基类构造函数)。 (此外,当执行初始化列表时,this 还无效,所以您不能访问任何成员。)

如果你想做其他类型的初始化工作,你可以改为在构造函数body中进行,此时对象被认为已经为this 有效:

A(this.name, int newAge) {
age = newAge;
}

另见:

关于flutter - 在 Dart 中将 Setter 与构造函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63964929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com