是否可以在构造函数中自动初始化来自父类的字段?
语法错误:
无法将参数初始值设定项“this.name”与任何字段匹配
class Type {
String name;
}
class Language extends Type {
String id;
Language(this.name) {
最佳答案
虽然您的情况很常见,但此时 dart language spec具体说:
Executing an initializing formal this.id causes the field id of the immediately surrounding class to be assigned the value of the corresponding actual parameter.
这实质上告诉我们构造函数参数中的 this.variable
表示法只对直接类中的变量有效,对任何父类无效。有几个可用的解决方案:第一个是在构造函数的主体内分配它:
class Type {
String name;
}
class Language extends Type {
String id;
Language(name) {
this.name = name;
}
}
或者,如果我们可以将父类更改为具有将初始化变量的构造函数,那么我们可以在子类中使用初始化列表:
class Type {
String name;
Type();
Type.withName(this.name);
}
class Language extends Type {
String id;
Language(name) : super.withName(name);
}
这是假设 Type
的默认构造函数没有自动初始化 name
的某些原因,因此我们创建了第二个命名构造函数。
关于dart - 如何自动初始化父字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12601620/