gpt4 book ai didi

generics - 如何在 Dart 中使用镜像获取泛型类型变量的具体类型?

转载 作者:行者123 更新时间:2023-12-03 20:50:23 25 4
gpt4 key购买 nike

假设我有一个像这样的 StringList

var myList = new List<String>();

如何确定 myListStringList 使用镜像?


我使用 ClassMirrortypeVariables 进行了尝试,但镜像似乎只描述了通用 List 类。

InstanceMirror im = reflect(myList); // InstanceMirror on instance of 'List'
ClassMirror cm = im.type; // ClassMirror on 'List'
print(cm.typeVariables['E']) // TypeVariableMirror on 'E'

我也在文档中找到了这一点,但我还没有找到访问 originalDeclaration 不会引发 NoSuchMethodErrorClassMirror 实例。

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 种可能的方法。

第一种方法是使用 is 运算符检查变量的类型,因为它比反射更高效:

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>();

Map typeArguments = reflect(myList).type.typeArguments;
print(typeArguments); // {Symbol("T"): ClassMirror on 'String'}

ClassMirror firstTypeArg = typeArguments[typeArguments.keys.first];
print(firstTypeArg.reflectedType); // String

关于generics - 如何在 Dart 中使用镜像获取泛型类型变量的具体类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14384865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com