Dart源码中接口内部是如何工作的

How do interfaces work internally in the Dart source code

如果我像这样在 Dart 中创建一个界面:

abstract class MyType {
  factory MyType() => MyConcreteSubtype();
  void doSomthing();
}

class MyConcreteSubtype implements MyType {
  @override
  void doSomthing() {
    print(42);
  }
}

当我运行以下代码时:

final myObject = MyType();
print(myObject.runtimeType); // MyConcreteSubtype

它打印 MyConcreteSubtype.

为什么会这样:

final myList = List();
print(myList.runtimeType); // List<dynamic>

还说是ListList源码是这样的:

abstract class List<E> implements EfficientLengthIterable<E> {
  external factory List([int? length]);
  // ...
}

除了 external 关键字,这与我所做的有何不同?当我的接口的 运行time 类型解析为它的具体实现类型时,List 的 运行time 类型如何仍然伪装成 List?无论如何,具体的 List 实现在哪里?我在 dart:collections 库中只能找到摘要 类 BaseListListMixin.

Dart 允许 classes 覆盖 runtimeType getter.

一些内部 platform-specific 实现类型这样做。例如,在 VM 平台库中有两个或三个不同的实现 classes 实现 int,但它们都声称具有类型 int。您永远不需要知道其中的区别。

我猜您正在 运行 上网。 JavaScript 编译后的代码有相反的问题:zero classes 实现了默认的 List,而是直接用 JavaScript Array。因此,没有正确的 class [].runtimeType 可以 return 一个 Type ,而只是 returns List 本身。那是 kind-of 作弊,但它也是最接近实际(嗯,non-existing)实现的现有超级 class。

总而言之,你不应该相信 runtimeType 并且你不应该 使用 runtimeType 除了 dart:mirrors(它不网络上不存在)。