如何获得泛型? [英] How to get generic Type?

查看:61
本文介绍了如何获得泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得泛型类的 Type 。理想情况下,我想要以下内容:

I would like to obtain the Type of a generic class. Ideally I'd like the following:

Type type = MyClass<int>;

但这会引发语法错误。
什么是访问此类型信息的正确方法?

But this is throws a syntax error. What is the proper way to get access this type information?

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

I know that I can get this type using runtimeType like so:

final foo = MyClass<int>();
Type type = foo.runtimeType;

但这需要对象的实例;

But this requires an instance of the object; which doesn't fit my use-case.

推荐答案

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

Dart doesn't support type arguments in class literals (https://github.com/dart-lang/sdk/issues/11923)

但是您可以编写一个小的通用帮助程序:

But you can write a small generic helper:

Type typeOf<T>() => T;

main() {
  Type type = typeOf<MyClass<int>>();
  print(type);
}

这篇关于如何获得泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆