我浏览了一下language documentation,发现Google Dart似乎不支持混合(接口中没有方法体,没有多重继承,没有类似Ruby的模块).关于这一点,我说得对吗?或者,有没有其他方法可以在DART中实现类似于Mixin的功能?

推荐答案

我很高兴地告诉大家,现在的答案是肯定的!

Mixin实际上只是子类和超类之间的增量.然后,您可以将该增量"混合"到另一个类中.

例如,考虑这个抽象类:

 abstract class Persistence {  
  void save(String filename) {  
   print('saving the object as ${toJson()}');  
  }  

  void load(String filename) {  
   print('loading from $filename');  
  }  

  Object toJson();  
 } 

然后,您可以将其混合到其他类中,从而避免了对继承树的污染.

 abstract class Warrior extends Object with Persistence {  
  fight(Warrior other) {  
   // ...  
  }  
 }  

 class Ninja extends Warrior {  
  Map toJson() {  
   return {'throwing_stars': true};  
  }  
 }  

 class Zombie extends Warrior {  
  Map toJson() {  
   return {'eats_brains': true};  
  }  
 } 

对混合定义的限制包括:

  • 不能声明构造函数
  • 超类是对象
  • 不包含对SUPERR的调用

一些额外的阅读material :

Dart相关问答推荐

dart 日期时差(分钟)

Flutter Getx - 未找到Xxx.您需要调用Get.put(Xxx()) - 但我已调用 Get.put(Xxx())

在 Flutter 中从树中临 timeshift 除时保留小部件状态

flutter: 使用提供程序时,状态在热重载时丢失

Flutter 中的with关键字

可调用云函数错误:响应缺少数据字段

如何将圆形边框设置为flutter上的MaterialButton?

如何在 Flutter/dart 中获取一周中特定日期的日期?

为什么这个文件会自动创建自己 generate_plugin_registrant.dart

有没有更好的方法来解析 Dart 中的 int

Dart 2:Future 和 Future 之间的区别

如何在 Dart 中将字符串转换为 utf8?

扩展一个只有一个工厂构造函数的类

Dart 是否有断点语句?

多次打印同一个字符而不循环

从 Dart Map 中删除选定的键

在 Dart 中升序和降序排序?

如何在 Dart 中读取控制台输入/标准输入?

如何停止 Dart 的 .forEach()?

在 Dart 中克​​隆list列表、map或set集合