1

根据有关'dart:mirror'文件bool isSubtypeOf(TypeMirror other)

  /**
   * Checks the subtype relationship, denoted by [:<::] in the language
   * specification. This is the type relationship used in [:is:] test checks.
   */
  bool isSubtypeOf(TypeMirror other);

如果我正确理解文档,"bool isSubtypeOf(TypeMirror other)"我认为它应该作为"operator is".

此代码按预期工作:

import "dart:mirrors";

void main() {
  var objectMirror = reflectType(Object);
  var result1 = objectMirror.isSubtypeOf(reflectType(bool));
  var result2 = Object is bool;
  print("Object is bool: $result1");
  print("Object is bool: $result2");
}

输出:

Object is bool: false
Object is bool: false

但我无法理解“这个结果是否正确”?

import "dart:mirrors";

void main() {
  var dynamicMirror = reflectType(dynamic);
  var result1 = dynamicMirror.isSubtypeOf(reflectType(bool));
  var result2 = dynamic is bool;
  print("dynamic is bool: $result1");
  print("dynamic is bool: $result2");
}

输出:

dynamic is bool: true
dynamic is bool: false
4

2 回答 2

3

运算符在is左侧获取一个对象实例,在右侧获取一个类型,并检查该对象是否是该类型的实例(或该类型的任何子类型)。测试Object is booldynamic is bool都给出错误,因为您正在测试 Type 对象是否是 bool 的实例。如果你写了Object is Type,那将是真的。

测试给出了预期的isSubtypeOf结果:Object 不是 bool 的子类型,dynamic 是 bool 的子类型。动态“类型”根据关系既是所有类型的子类型,又是超类型<:

就我个人而言,我不认为dynamic是一种类型,而是一种类型的替代品。这是程序员说“相信我,我知道我在做什么”的方式,这就是为什么任何涉及动态的测试通常都会说“是”的原因。它代表了程序员省略写的一些类型,但如果它们在那里,那将是完全正确的。

至于标题问题,关系是:

(reflect(o).type.isSubtypeOf(reflectType(Foo))) == (o is Foo)
于 2014-04-10T07:32:57.223 回答
1

对我来说看起来像一个错误:

/**
 * Checks the subtype relationship, denoted by [:<::] in the language
 * specification. This is the type relationship used in [:is:] test checks.
 */
bool isSubtypeOf(TypeMirror other);
于 2014-04-09T11:19:51.893 回答