Accordingly to the 'dart:mirror' documentation on 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);

If I correct understand the documentation on "bool isSubtypeOf(TypeMirror other)" than I think that it should work as "operator is".

This code work as expected:

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");
}

Output:

Object is bool: false
Object is bool: false

But I cannot understand "is this result correct or not"?

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");
}

Output:

dynamic is bool: true
dynamic is bool: false
有帮助吗?

解决方案

The is operator takes an object instance on the left and a type on the right, and checks whether the object is an instance of the type (or any subtype of the type). The tests Object is bool and dynamic is bool both give false, because you are testing whether a Type object is an instance of bool. If you wrote Object is Type, it would be true.

The isSubtypeOf tests give the expected results: Object is not a subtype of bool, and dynamic is a subtype of bool. The dynamic "type" is both a subtype and a supertype of all types according to the <: relation.

Personally I don't see dynamic as a type, as much as an alternative to having a type. It's the programmer's way of saying "trust me, I know what I am doing", which is why any test involving dynamic will generally say "yes". It represents some type, or types, that the programmer omitted to write, but which would be perfectly correct if they were there.

As for the title question, the relation is:

(reflect(o).type.isSubtypeOf(reflectType(Foo))) == (o is Foo)

其他提示

Looks like a bug to me:

/**
 * Checks the subtype relationship, denoted by [:<::] in the language
 * specification. This is the type relationship used in [:is:] test checks.
 */
bool isSubtypeOf(TypeMirror other);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top