如何使用`DartType`从`analyzer`包中获取泛型类型的子类型? [英] How to get the subtypes of a generic type using `DartType` from `analyzer` package?
问题描述
如何使用分析器包中
的 List< String>
,我想得到 String
。如果类型为 generic
,也将有用。
for example if the type is List<String>
, I would like to get String
. Also will be useful to get if the type is generic
.
另一个更复杂的例子是 Map< String,String>
其中我想获得子类型的列表,在这种情况下: [String,String]
/ p>
Another more complex example would be Map<String, String>
where I want to get a list of the subtypes, in this case: [String, String]
.
推荐答案
这个有点棘手 - 因为 DartType
实际上本身有一些超类型 - 您会感兴趣的是 ParameterizedType
:
This one is a little tricky - because DartType
actually itself has some super types - the one that will interest you here is ParameterizedType
:
import 'package:analyzer/dart/element/type.dart';
Iterable<DartType> getGenericTypes(DartType type) {
return type is ParameterizedType ? type.typeArguments : const [];
}
我不知道是否可以知道如果类型是通用的 - 毕竟它只是一个类型。但您可以再次使用 ClassElement
检查类型是否接受类属参数:
I don't know if it's possible to know if the type is generic - after all, it's just a type. But you can check if the type accepts generic parameters, again, using ClassElement
:
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
bool canHaveGenerics(DartType type) {
final element = type.element;
if (element is ClassElement) {
return element.typeParameters.isNotEmpty;
}
return false;
}
希望有所帮助!
这篇关于如何使用`DartType`从`analyzer`包中获取泛型类型的子类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!