[英]What is the relationship between generics and actual types ? (dart)
When defining base classes, I find that generics and actual types are somewhat different and confusing. 在定义基类时,我发现泛型和实际类型有些不同并且令人困惑。
Like the following: 如下所示:
When I use basic types, the code works well. 当我使用基本类型时,代码运行良好。
void main() {
var aa = AA.name("11");
aa.test();
}
class AA<T> {
T field;
AA.name(this.field);
void test() {
print(field.runtimeType);
print(T);
print(field.runtimeType == T);
}
}
this result: 结果:
String
String
true
But when I use other types, things change. 但是当我使用其他类型时,情况会改变。
void main() {
var aa = AA.name(["11"]);
aa.test();
}
class AA<T> {
T field;
AA.name(this.field);
void test() {
print(field.runtimeType);
print(T);
print(field.runtimeType == T);
}
}
the result: 结果:
List<String>
List<String>
false
Both are List < String > types. 两者都是List <String>类型。 Why are the corresponding types different? 为什么对应的类型不同?
Try change this line 尝试更改此行
print(field.runtimeType == T);
to 至
print(field.runtimeType.toString() == T.toString());
It will return true. 它将返回true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.