当它是通用的时,我在检查变量的类型时遇到了一些问题。
例子T
是List<MyClass>
T is List<MyClass>
//return false
T is List
//return false
最后,我必须使用一些愚蠢的方法才能得到正确的答案
T.toString() == "List<MyClass>"
//return true
有没有任何标准的方法来处理它,或者我需要坚持我的愚蠢方法,直到官方发布?
import 'package:type_helper/type_helper.dart';
void main() {
var list1 = [0];
func(list1);
var list2 = [MyClass<Map<String, int>>()];
func(list2);
var list3 = ['Hello'];
func(list3);
}
void func<T>(T object) {
if (isTypeOf<T, List<int>>()) {
print('T is subtype of List<int>');
} else if (isTypeOf<T, List<MyClass>>()) {
print('T is subtype of List<MyClass>');
if (isTypeOf<T, List<MyClass<Map<String, int>>>>()) {
print('O, yes, T is subtype of List<MyClass<Map<String, int>>>>');
}
} else {
print('Oh, no. T is not a subtype of valid type');
}
}
class MyClass<Elem> {
MyClass() {
if (isTypeOf<Elem, Map<String, int>>()) {
print('Elem is subtype of Map<String, int>');
}
}
}
结果:
T is subtype of List<int>
Elem is subtype of Map<String, int>
T is subtype of List<MyClass>
O, yes, T is subtype of List<MyClass<Map<String, int>>>>
Oh, no. T is not a subtype of valid type