我希望能够从通用函数内部构造一个对象。我尝试了以下方法:
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'
。
注意:我不能使用镜子,因为我正在使用带有飞镖的飞镖。
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句