How to perform runtime type checking in Dart?

旧巷老猫 提交于 2019-11-29 23:31:13
Patrick

The instanceof-operator is called is in Dart. The spec isn't exactly friendly to a casual reader, so the best description right now seems to be http://www.dartlang.org/articles/optional-types/.

Here's an example:

class Foo { }

main() {
  var foo = new Foo();
  if (foo is Foo) {
    print("it's a foo!");
  }
}

Dart Object type has a runtimeType instance member (source is from dart-sdk v1.14, don't know if it was available earlier)

class Object {
  //...
  external Type get runtimeType;
}

Usage:

Object o = 'foo';
assert(o.runtimeType == String);

As others have mentioned, Dart's is operator is the equivalent of Javascript's instanceof operator. However, I haven't found a direct analogue of the typeof operator in Dart.

Thankfully the dart:mirrors reflection API has recently been added to the SDK, and is now available for download in the latest Editor+SDK package. Here's a short demo:

import 'dart:mirrors'; 

getTypeName(dynamic obj) {
  return reflect(obj).type.reflectedType.toString();
}

void main() {
  var val = "\"Dart is dynamically typed (with optional type annotations.)\"";
  if (val is String) {
    print("The value is a String, but I needed "
        "to check with an explicit condition.");
  }
  var typeName = getTypeName(val);
  print("\nThe mirrored type of the value is $typeName.");
}

There are two operators for type testing: E is T tests for E an instance of type T while E is! T tests for E not an instance of type T.

Note that E is Object is always true, and null is T is always false unless T===Object.

object.runtimeType returns the type of object

For example:

print("HELLO".runtimeType); //prints String
var x=0.0;
print(x.runtimeType); //prints double

A small package can help solve some problems.

import 'dart:async';

import 'package:type_helper/type_helper.dart';

void main() {
  if (isTypeOf<B<int>, A<num>>()) {
    print('B<int> is type of A<num>');
  }

  if (!isTypeOf<B<int>, A<double>>()) {
    print('B<int> is not a type of A<double>');
  }

  if (isTypeOf<String, Comparable<String>>()) {
    print('String is type of Comparable<String>');
  }

  var b = B<Stream<int>>();
  b.doIt();
}

class A<T> {
  //
}

class B<T> extends A<T> {
  void doIt() {
    if (isTypeOf<T, Stream>()) {
      print('($T): T is type of Stream');
    }

    if (isTypeOf<T, Stream<int>>()) {
      print('($T): T is type of Stream<int>');
    }
  }
}

Result:

B<int> is type of A<num> B<int> is not a type of A<double> String is type of Comparable<String> (Stream<int>): T is type of Stream (Stream<int>): T is type of Stream<int>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!