飞镖规格说明:
已知类型信息反映了运行时对象的类型,并且可能始终通过动态类型检查构造(其他语言中的instanceOf,casts,typecase等的类比)来查询。
听起来很棒,但没有像instanceof
一样的操作员。那么我们如何在Dart中执行运行时类型检查?有可能吗?
instanceof-operator在Dart中称为is
。规范对于一个随意的读者来说并不是很友好,所以现在最好的描述似乎是http://www.dartlang.org/articles/optional-types/。
这是一个例子:
class Foo { }
main() {
var foo = new Foo();
if (foo is Foo) {
print("it's a foo!");
}
}
正如其他人所提到的,Dart的is
运算符相当于Javascript的instanceof
运算符。但是,我没有找到Dart中typeof
算子的直接类比。
值得庆幸的是,dart:mirrors reflection API最近已添加到SDK中,现在可以在latest Editor+SDK package下载。这是一个简短的演示:
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.");
}
Dart Object
类型有一个runtimeType
实例成员(来源来自dart-sdk
v1.14,不知道它是否早期可用)
class Object {
//...
external Type get runtimeType;
}
用法:
Object o = 'foo';
assert(o.runtimeType == String);
有两个类型测试运算符:E is T
测试E是类型T的实例,而E is! T
测试E不是类型T的实例。
请注意,E is Object
总是如此,除非null is T
,否则T===Object
总是假的。
object.runtimeType
返回对象的类型
例如:
print("HELLO".runtimeType); //prints String
var x=0.0;
print(x.runtimeType); //prints double
小包装可以帮助解决一些问题。
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>');
}
}
}
结果:
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>