generics - 如何从 Dart/Flutter 中的泛型函数调用命名构造函数

我希望能够从通用函数内部构造一个对象。我尝试了以下方法:

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/

相关文章:

dart - 在 SnackBarAction onPressed 上 flutter 小吃吧

dart - 如何在 Dart 中将 Class 对象转换为数据结构 `Map` 或 `List o

dart - Flutter,如何让我的原 Material 纽扣更大更紧密地组合在一起。

android - Flutter:使用 Sliver 小部件时如何在滚动时隐藏 BottomApp

dart - Flutter如何将容器背景设置为透明色

dart - 如何在 Dart 中通过 async* 传输错误?

dart - Column 内展开的小部件未展开,而是不可见

dart - Dart 类中带下划线的命名参数

dart - 向 Flutter 中的计算函数发送多个参数

dart - 我们可以使用 Flutter 或 Dart 制作 Web 应用程序或网站吗