如何使用Dart中的镜像获取通用类型变量的具体类型? [英] How can I get the concrete type of a generic type variable using mirrors in Dart?
问题描述
假设我有 List
的 String
,就像这样。
var myList = new List< String>();
如何知道 myList
$ c
我尝试使用 ClassMirror
的 typeVariables
,但镜像似乎只是描述gerneric List
类。
InstanceMirror im = reflect(myList); // InstanceMirror on'List'的实例
ClassMirror cm = im.type; // ClassMirror on'List'
print(cm.typeVariables ['E'])// TypeVariableMirror on'E'
我在文档中也发现了这一点,但我还没有找到一个 ClassMirror
实例,其中访问 originalDeclaration
不会抛出 NoSuchMethodError
。
final ClassMirror
对于大多数类,它们都是这个类型的原始声明的镜像。是他们自己的原始声明。然而,对于通用的
类,有原始类的
声明(其具有未绑定的类型变量)和实例化
(具有绑定类型变量的泛型类)之间的区别。
2种可能的方法。
第一种方法是使用是
运算符来检查变量的类型,因为它比反射更有效: p>
var myList = new List< String>();
print(myList is List< int>); // false
print(myList is List< String>); // true
第二种方法是使用 ClassMirror.typeArguments :
import'dart:mirrors';
var myList = new List< String>();
映射typeArguments = reflect(myList).type.typeArguments;
print(typeArguments); // {Symbol(T):ClassMirror on'String'}
ClassMirror firstTypeArg = typeArguments [typeArguments.keys.first];
print(firstTypeArg.reflectedType); // String
Assuming I have a List
of String
s like this.
var myList = new List<String>();
How can I figure out that myList
is a List
of String
s using mirrors?
I tried it using the typeVariables
of ClassMirror
but the mirror seems to just describe the gerneric List
class.
InstanceMirror im = reflect(myList); // InstanceMirror on instance of 'List'
ClassMirror cm = im.type; // ClassMirror on 'List'
print(cm.typeVariables['E']) // TypeVariableMirror on 'E'
I also found this in the documentation but I have yet to find a ClassMirror
instance where accessing originalDeclaration
doesn't throw a NoSuchMethodError
.
final ClassMirror originalDeclaration
A mirror on the original declaration of this type.
For most classes, they are their own original declaration. For generic classes, however, there is a distinction between the original class declaration, which has unbound type variables, and the instantiations of generic classes, which have bound type variables.
2 possible methods.
The first method is to check the variable's type using is
operator, as it's more performant than reflection:
var myList = new List<String>();
print(myList is List<int>); // false
print(myList is List<String>); // true
The second method is to use ClassMirror.typeArguments:
import 'dart:mirrors';
var myList = new List<String>();
Map typeArguments = reflect(myList).type.typeArguments;
print(typeArguments); // {Symbol("T"): ClassMirror on 'String'}
ClassMirror firstTypeArg = typeArguments[typeArguments.keys.first];
print(firstTypeArg.reflectedType); // String
这篇关于如何使用Dart中的镜像获取通用类型变量的具体类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!