如何获得泛型类型?

Rém*_*let 7 dart flutter

我想获得Type一个泛型类.理想情况下,我想要以下内容:

Type type = MyClass<int>;
Run Code Online (Sandbox Code Playgroud)

但这会引发语法错误.获取此类型信息的正确方法是什么?

我知道我可以runtimeType像这样使用这种类型:

final foo = MyClass<int>();
Type type = foo.runtimeType;
Run Code Online (Sandbox Code Playgroud)

但这需要一个对象的实例; 这不适合我的用例.

Xav*_*ier 16

Dart不支持类文字中的类型参数(https://github.com/dart-lang/sdk/issues/11923)

但是你可以写一个小的通用助手:

Type typeOf<T>() => T;

main() {
  Type type = typeOf<MyClass<int>>();
  print(type);
}
Run Code Online (Sandbox Code Playgroud)

  • 这实际上很聪明 (2认同)