根据我的以下代码,我想要一个该类的构造函数,该构造函数Hero
将一个Stats
类作为可选参数,并根据其构造函数 具有默认值( 该构造函数通过一个可选名称将其运行状况和攻击字段设置为100和10参数),而不是null。
void main() {
Hero hero = Hero("Foo");
print('${hero.name} : HP ${hero.stats.health}');
}
class Stats {
Stats({this.health = 100, this.attack = 10});
double health;
double attack;
}
class Hero {
// error: The default value of an optional parameter must be constant
Hero(this.name,[this.stats = Stats()]);
String name;
Stats stats;
}
我尝试过的更多操作:
class Hero {
// error: Can't have a const constructor for a class with non-final fields
Hero(this.name,[this.stats = const Stats()]);
String name;
Stats stats;
}
class Hero {
// error: stats initialized as null
Hero(this.name,[this.stats]);
String name;
Stats stats = Stats();
}
以下代码有效,但没有统计信息作为可选参数:
class Hero {
Hero(this.name);
String name;
Stats stats = Stats();
}
(由于@jamesdlin在评论中链接到他的答案而致谢)
通常,如果没有const构造函数,您可以改为使用空默认值(或其他一些合适的哨兵值),然后在以后设置所需的值:
class Foo {
Bar bar;
Foo({Bar bar}) : bar = bar ?? Bar();
}
(请注意,与直接设置默认值相比,使用此方法显式传递null作为参数将产生不同的效果。也就是说,使用此方法将Foo(bar:null)初始化为bar(),而使用常规方法默认值,它将把bar初始化为null。但是,在某些情况下,这种方法的行为可能更理想。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句