【发布时间】:2021-11-03 23:16:44
【问题描述】:
以下代码不会运行:
class X{
double? x;
}
mixin Y{
double? y;
}
class Z extends X with Y {
double? z;
Z(this.x, this.y, this.z)
}
编译器会抱怨 this.x 和 this.y 不是封闭类中的字段:
lib/physicalObject.dart:20:10: Error: 'x' isn't an instance field of this class.
Z(this.x, this.y, this.z)
^
lib/physicalObject.dart:20:18: Error: 'y' isn't an instance field of this class.
Z(this.x, this.y, this.z)
^
当然不是这样,字段x和y是继承自父类和mixin的。我可以在子类 Z 中使用这些字段,似乎只有构造函数在接受这些作为参数时存在问题。但为什么呢?
【问题讨论】:
-
如果
X的默认构造函数也初始化了x,你期望会发生什么?如果x是final会怎样? -
很好的问题,我不确定,但是当我定义以下构造函数时会出现同样的问题: Z({ double?x, double?y, double?z}) { this.x = x;这个.y = y;这个.z = z; } 然而,dart 让我这样做
-
您的最后一个示例定义明确;当
Z的构造函数体执行时,基类已经被初始化。 (如果X.x是final,您的示例将失败。)请参阅 stackoverflow.com/a/63319094。 -
你是说如果我写Z(this.z),z是在基类初始化之前设置的吗?我假设 Z(this.z) 和 Z(double?z) {this.z = z} 基本上是同一事物的不同符号。
-
是的,这就是我要说的。
Z(this.z)和Z(double? z) { this.z = z; }不一样,因为构造函数体不能用于初始化(非late)final字段。
标签: dart inheritance mixins