为何_Map<String, String>不在[Map<String, String>, bool]中?Dart类型检查问题
问题:Dart运行时类型检查中Map实例无法匹配Map<String, String>类型的原因?
我需要进行运行时类型检查,编写了如下Dart代码:
void main() { final type = [Map<String, String>, bool]; final mapTest = {"A": "B"}; if (type.contains(mapTest.runtimeType)) { print("yes"); } else { print("no, ${mapTest.runtimeType} is not in $type"); } bool boobool = true; if (type.contains(boobool.runtimeType)) { print("yes, ${boobool.runtimeType} is in $type"); } else { print("no, ${mapTest.runtimeType} is not in $type"); } }
预期mapTest能通过检查,但实际未通过,代码运行输出:
no, _Map<String, String> is not in {Map<String, String>, bool} yes, bool is in {Map<String, String>, bool}
请问这是什么原因?
原因分析与解决方案
核心原因
Dart中用字面量{"A": "B"}创建的Map,实际运行时类型是_Map<String, String>——这是Dart SDK内部封装的具体实现类;而你列表里的Map<String, String>是抽象类Map的类型对象,两者并非同一个对象,所以List.contains()的严格相等检查会失败。
而bool是具体类型,字面量true的运行时类型就是bool本身,所以匹配成功。
解决方案
1. 使用is关键字(推荐)
is是Dart原生的类型检查关键字,会自动判断实例是否属于目标类型(包括其子类/实现类),完全符合面向对象的多态逻辑:
void main() { final mapTest = {"A": "B"}; if (mapTest is Map<String, String>) { print("yes"); } else { print("no, ${mapTest.runtimeType} is not Map<String, String>"); } }
2. 用类型对象的isAssignableFrom方法检查
如果必须保留类型列表的方式,可以通过Type.isAssignableFrom()判断实例类型是否能赋值给目标类型:
void main() { final types = [Map<String, String>, bool]; final mapTest = {"A": "B"}; if (types.any((targetType) => targetType.isAssignableFrom(mapTest.runtimeType))) { print("yes"); } else { print("no, ${mapTest.runtimeType} is not in $types"); } }
内容的提问来源于stack exchange,提问作者TSR
相关产品推荐
相关产品推荐

