我希望能够从通用函数内部构造一个对象。我尝试了以下方法:
abstract class Interface
{
Interface.func(int x);
}
class Test implements Interface
{
Test.func(int x){}
}
T make<T extends Interface>(int x)
{
// the next line doesn't work
return T.func(x);
}
然而,这不起作用。我收到以下错误消息:The method 'func' isn't defined for the class 'Type'
.
Note:我无法使用镜子,因为我正在使用 dart 和 flutter。
Dart 不支持从泛型类型参数实例化。如果您想使用命名或默认构造函数(T()
也不起作用)。
可能有一种方法可以在服务器上做到这一点,其中dart:mirrors
(反射)可用(我自己还没有尝试过),但在 Flutter 或浏览器中不可用。
您需要维护工厂函数的类型映射
void main() async {
final double abc = 1.4;
int x = abc.toInt();
print(int.tryParse(abc.toString().split('.')[1]));
// int y = abc - x;
final t = make<Test>(5);
print(t);
}
abstract class Interface {
Interface.func(int x);
}
class Test implements Interface {
Test.func(int x) {}
}
/// Add factory functions for every Type and every constructor you want to make available to `make`
final factories = <Type, Function>{Test: (int x) => Test.func(x)};
T make<T extends Interface>(int x) {
return factories[T](x);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)