如何从Dart/Flutter中的泛型函数调用命名构造函数 [英] How to call a named constructor from a generic function in Dart/Flutter

查看:667
本文介绍了如何从Dart/Flutter中的泛型函数调用命名构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to be able to construct an object from inside a generic function. I tried the following:

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'.

However, this doesn't work. And I get the following error message: The method 'func' isn't defined for the class 'Type'.

注意:我无法使用镜子,因为我正在使用带有飞镖的飞镖.

Note: I cannot use mirrors because I'm using dart with flutter.

推荐答案

Dart不支持从泛型类型参数实例化.想要使用命名构造函数还是默认构造函数都没关系(T()也不起作用).

Dart does not support instantiating from a generic type parameter. It doesn't matter if you want to use a named or default constructor (T() also does not work).

服务器上可能有一种方法,其中dart:mirrors(反射)可用(尚未尝试过),但在Flutter或浏览器中没有.

There is probably a way to do that on the server, where dart:mirrors (reflection) is available (not tried myself yet), but not in Flutter or the browser.

您需要维护类型到工厂功能的映射

You would need to maintain a map of types to factory functions

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);
}

这篇关于如何从Dart/Flutter中的泛型函数调用命名构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆