我希望能够从通用函数内部构造一个对象。我尝试了以下方法:
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);
}
但是,这不起作用。我收到以下错误消息:没有为类“Type”定义方法“func”
。
注意:我不能使用镜子,因为我正在使用带有 flutter 的 Dart 。
最佳答案
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);
}
https://stackoverflow.com/questions/55237006/