在 Dart 中,有一個神奇的類型,叫作 mixin。github
它和 class 比較相似,但它沒有構造函數。bash
經過 mixin,能夠擴展一個類的屬性和功能,使得類具備 Mixin 類的屬性和函數 API。函數
使用 mixin
關鍵字來定一個 Mixin 類:post
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');
}
}
}
複製代碼
經過 with
關鍵來使用 Mixin 類擴展一個類。ui
在 Dart 中,一個類支持擴展無限個 Mixin,它們使用 ,
來分隔彼此。spa
class Maestro extends Person
with Musical, Aggressive, Demented {
Maestro(String maestroName) {
name = maestroName;
canConduct = true;
}
}複製代碼