如何检查对象的类是否包含mixin?例如:

class AClass extends Object with MyMixin {}
class BClass extends Object              {}

classIncludesMixin(new AClass(), 'MyMixin'); // => true
classIncludesMixin(new BClass(), 'MyMixin'); // => false

为了使其正常工作,此classIncludesMixin()方法应该是什么?

最佳答案

您可以简单地使用类型检查o is MyMixin(对于继承和实现也是如此)。

如果确实需要检查mixin子句,则必须使用dart:mirrors:

bool classIncludesMixin(o, String mixinName) {
  var c = reflect(o).type;
  while (c != null) {
    var m = c.mixin;
    if (c != m && m.simpleName == new Symbol(mixinName)) return true;
    c = c.superclass;
  }
  return false;
}

09-19 00:50