flutter - 如何将类型从一个类“传递”到另一个类?
问题描述
请看下面的样本
class Foo<T> {
Type get type => T;
}
class Bar<T> {}
void main() {
final foo = Foo<String>();
final Type type = foo.type;
final bar = Bar<type>(); // <= error on [type]:
///The name 'type' isn't a type so it can't be used as a type argument - line 10
}
我知道下面的基本方法,但需要提前知道Type
Bar fromFoo<T>(Foo<T> foo) => Bar<T>();
在事先不知道类型的情况下创建Bar
相同类型的正确方法是什么?Foo
解决方案
Francesco Iapicca通过在的构造函数中传递Foo
类型来试试这个代码片段:Bar
class Foo<T> {
Type get type => T;
}
class Bar {
final Type t;
Bar({this.t});
}
void main() {
final foo = Foo<String>();
final bar = Bar(t: foo.type);
}
注意t
变量 in的类型Bar
与type
from相同Foo
推荐阅读
- javascript - Express:已解决的 Promise 将接听电话
- reactjs - Bootstrap 下拉菜单不适用于 React 路由器
- r - 数据框中的错误:选择了未定义的列
- sql - sql查询结果格式
- java - 如何使用@RequestParam 将数组的默认值设置为空
- javascript - 慢慢自动滚动到 div 的底部
- java - 如何在片段中放置或替换列表
- java - Docker 容器中的 AWS SAM CLI 导致 ClassNotFoundException
- email - Auth0:让用户重新发送验证邮件
- c# - 无法将 Entity Framework Core 迁移添加到 .NET Standard 2.0 项目