简单的情况,int确实是一个数字。
我正在创建一个通用的class test<T>
我想测试T以查看它是否继承自数字(或者在Dart的情况下为num)。
基于对象,文档中的Object > num > int
,所以起初我在想:如果T is num
是T
,int
会起作用。测试int is num
显示错误。必须有另一个关键字我需要使用而不是is
来确定它是否是特定类的子代。
我试图设置它,如果T是num的子节点,它将处理比较不同于它们是字符串。
对我来说,这可以追溯到is-a的多态性 - 继承设计并且具有一种关系。
如何测试类型及其类型参数。
import 'package:type_helper/type_helper.dart';
void main() {
var test = Test<int>();
test.testAgain<String>();
if (isTypeOf<Test, Test>()) {
print('<Test> is type of <Test>. Haha. Well it is obvious. :-)');
}
}
class Test<T> {
Test() {
if (isTypeOf<T, int>()) {
print('<T> is type of <int>. It is very good. :-)');
}
}
void testAgain<T2>() {
if (isTypeOf<T2, String>()) {
print('<T2> is type of <String>. It is also good. :-)');
}
}
}
结果:
<T> is type of <int>. It is very good. :-)
<T2> is type of <String>. It is also good. :-)
<Test> is type of <Test>. Haha. Well it is obvious. :-)