Dart 中,有一个神奇的类型,叫做 mixin。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/16451.html
它和 class 比较类似,但它没有构造函数。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/16451.html
通过 mixin,可以扩展一个类的属性和功能,使得类具有 Mixin 类的属性和函数 API。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/16451.html
如何定义一个 Mixin?
使用 mixin
关键字来定一个 Mixin 类:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/16451.html
mixin Musical {
bool canPlayPiano = false;
bool canCompose = false;
bool canConduct = false;
void entertainMe() {
if (canPlayPiano) {
print('Playing piano');
} else if (canConduct) {
print('Waving hands');
} else {
print('Humming to self');
}
}
}
复制代码
如何使用 Mixin?
通过 with
关键来使用 Mixin 类扩展一个类。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/16451.html
在 Dart 中,一个类支持扩展无限个 Mixin,它们使用 ,
来分隔彼此。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/16451.html
class Maestro extends Person
with Musical, Aggressive, Demented {
Maestro(String maestroName) {
name = maestroName;
canConduct = true;
}
}
作者:CoorChice
来源:掘金文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/16451.html