【问题标题】:Dart: checking if an object implements interfaceDart:检查对象是否实现接口
【发布时间】:2020-06-02 18:05:42
【问题描述】:

我有以下类和接口:

class Place extends Entity
    with ChangeNotifier, FieldGetters
    implements Scannable, Likable {
// ...some stuff
}

abstract class Likable {
// ... some stuff
}

Entity 只是其他类的基类。

所以,问题是我想检查实现Likable 接口的对象是否属于Place 类。为此,我使用以下代码:

logger.i('likable is ${like.likable.runtimeType}');
logger.i('likable is Place: ${like.likable is Place}');

第一行按预期工作并显示以下输出:

I/flutter ( 1635): [38;5;12m┌───────────────────────────────────────────────────────────────────────────────[0m
I/flutter ( 1635): [38;5;12m├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄[0m
I/flutter ( 1635): [38;5;12m│ ???? likable is Place[0m
I/flutter ( 1635): [38;5;12m└───────────────────────────────────────────────────────────────────────────────[0m

但是,第二行代码表现得很奇怪,显示如下:

I/flutter ( 1635): [38;5;12m┌───────────────────────────────────────────────────────────────────────────────[0m
I/flutter ( 1635): [38;5;12m├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄[0m
I/flutter ( 1635): [38;5;12m│ ???? likable is Place: false[0m
I/flutter ( 1635): [38;5;12m└───────────────────────────────────────────────────────────────────────────────[0m

官方文档建议可以通过is关键字检查接口继承。我很困惑。在这种情况下如何检查接口继承?

飞镖v2.8.1

颤动v1.17.0

【问题讨论】:

标签: flutter inheritance dart interface


【解决方案1】:

在 Dart 中,一个类只能从一个超类(PlaceEntity)和implement 从多个(即从这些类中获取函数)继承。

据我从你的描述中了解到,你正在做这样的事情(你可以运行它here)。

class Person extends LivingCreature implements Mammal{
  final _name;
  void _toDrinkMilk(){
    print("I drink milk as a person!");
  }
  Person(this._name);
}

class Mammal {
  void _toDrinkMilk(){
    print("I drink milk!");
  }
}

class LivingCreature {

  void _toLive(){
    print("I live!");
  }
}

void main() {
  final bob = Person('Bob');
  final mammal = Mammal();
  print(mammal is LivingCreature);
  print(bob.runtimeType);
  bob._toDrinkMilk();
  bob._toLive();
  print('Bob is mammal: ${bob is Mammal}');
  print('Mammal is Person: ${mammal is Person}');
}

这段代码产生以下输出:

true
Person
I drink milk as a person!
I live!
Bob is mammal: true
Mammal is Person: false

所以,现在让我们谈谈你的情况,你的like.likable 应该是一个Likable 抽象类(我假设)。 Place同时实现了Likable,所以它应该实现Likable的所有方法。

现在,您试图询问 Dart 的类型是 Likable(不扩展或实现任何东西)是 Place,即日志中给出的 false

如果是class Likable extends Place {...,那么在日志中,like.likable is Place 将等于 true

更多关于extends、implements,可以参考Dart docs

附:我没有把 Mammal 抽象成在 print() 中快速实例化它

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 2012-04-27
    • 1970-01-01
    相关资源
    最近更新 更多