dart - 如何编写一个可以添加任意数量的类的mixin,同时可以访问某些保证变量?
问题描述
如何编写一个可以添加任意数量的类的mixin,同时可以访问某些保证变量?
例如,这里的答案是可以的,但是如果希望 Comedian mixin 不仅对 Person 类可用,而且对任何具有int age
变量的类可用怎么办?
解决方案
答案是通过一个界面。接口基本上是一个抽象类,您可以通过 implements 而不是 extends 关键字使用它。虽然一个类只能扩展一个父类,但它可以实现任意数量的接口。
这是一个具体的例子:
void main() {
final person = Bob();
print(person.age);
print(person.ageInside);
// output will be 31, 13
final yogiBear = Yogi();
print(yogiBear.age);
print(yogiBear.ageInside);
// output will be 40, 22
}
abstract class MortalCreature {
int age;
MortalCreature(this.age);
}
mixin Comedian on MortalCreature {
// no need to declare age variable here, it finds it through `on`
int get ageInside {
return age - 18;
}
}
class Person implements MortalCreature {
int age;
int get ageInside {
return age;
}
Person(this.age);
}
class Bear implements MortalCreature {
int age;
Bear(this.age);
}
class Bob extends Person with Comedian {
Bob() : super(31);
}
class Yogi extends Bear with Comedian {
Yogi() : super(40);
}
推荐阅读
- python - 无法使用 requests.get() 方法从 django rest api 获得响应
- youtube-data-api - Youtube data api V3 插入聊天消息错误
- javascript - 如何在 NPM 模块中呈现自定义视图?
- css - Webpack 构建成功,但 styles.css 文件样式未反映
- android - 如何使用 AndroidViewClient/dump 命令进行多设备转储?
- python - 逻辑回归:ValueError:未知标签类型:“连续”
- c++ - 如何告诉 VBO 处理给定的数据?(布模拟)
- vtigercrm - vtiger 从 7.0.1 升级到 7.1.0 导致非法请求
- java - 在 Spring App 中调用未使用的 Bean
- maven - 通过 maven API 获取版本控制