gpt4 book ai didi

constructor - 在 Dart 中,您可以从构造函数中调用另一个构造函数吗

转载 作者:行者123 更新时间:2023-12-03 12:12:10 26 4
gpt4 key购买 nike

也就是说,我试图从另一个构造函数中调用一个构造函数,然后进一步构造。我无法从文档中弄清楚是否可以完成。

这是一个人为的例子,以防万一:

class Chipmunk {

Chipmunk.named(this.name);

Chipmunk.famous() {
this.named('Chip'); // <-- What, if anything, goes here?
this.fame = 1000;
}
}

var chip = new Chimpmunk.famous();

最佳答案

有两种可能的方法来做到这一点:

class Chipmunk {
String name;
int fame;

Chipmunk.named(this.name, [this.fame]);

Chipmunk.famous1() : this.named('Chip', 1000);
factory Chipmunk.famous2() {
var result = new Chipmunk.named('Chip');
result.fame = 1000;
return result;
}
}
Chipmunk.famous1()是一个重定向构造函数。您不能在此分配属性,因此您正在调用的构造函数必须允许您要设置的所有属性。这就是我添加 fame 的原因作为可选参数。在这种情况下,您可以制作 namefame最终的。
Chipmunk.famous2()是一个工厂构造函数,可以只创建你想要的实例。在这种情况下, fame不能是最终的(显然,如果您在 fame 构造函数中使用了 named 参数,则可能是最终的)。

第一个变体可能是您的用例的首选变体。

这是语言规范中的文档:

A generative constructor consists of a constructor name, a constructor parameter list, and either a redirect clause or an initializer list and an optional body.



https://www.dartlang.org/docs/spec/latest/dart-language-specification.html#h.flm5xvbwhs6u

关于constructor - 在 Dart 中,您可以从构造函数中调用另一个构造函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20015249/

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