【问题标题】:Is there a way to map strings to types in Dart?有没有办法将字符串映射到 Dart 中的类型?
【发布时间】:2019-01-08 16:47:14
【问题描述】:

我想保留一个字符串到已定义类的常量映射,这些类都继承自单个类 A:

class A {}
class B extends A {}
class C extends A {}
class D extends A {}

const strToType = {
  'str1': B,
  'str2': C,
  'str3': C,
  'str4': D,
  // etc.
};

因此,我假设这张地图采用Map<String, Type> 的形式,我什至尝试明确指出:<String, Type>{ /*...*/ }

不过,我不能像在 Python 等其他语言中那样使用此映射来动态决定创建哪个对象:

A variable = new strToType[someString](args);

在这种情况下,Dart 检查器显示错误 strToType is not a class

我尝试将 strToType[someString] 括在括号中,然后它会抱怨 new ( 部分。

实现我在 Dart 中所做工作的最佳方式是什么?我想避免大量的 switch 语句和代码重复,因为BCD 具有相同的构造接口,而且不仅仅是 3 个类。

编辑:为了清楚起见,在我的情况下,类的字符串标识符只会在运行时知道,我将收到一个字符串流,并基于此创建一个 @ 987654331@,其中元素是A 的特殊后代。

【问题讨论】:

  • 您希望通过字符串和类型之间的映射最终获得什么?常规继承/多态还不够吗?
  • @nbro 在我建立继承链后,我想在运行时决定我将使用哪些后代进行数据处理

标签: dictionary types dart


【解决方案1】:

Dart Type 对象是表示类型的不透明标记。它们不是类型本身。 你不能在需要类的地方使用Type 对象,所以你不能使用new TypeVar()TypeVar.staticMember

如果你想存储一种方法来创建子类的对象,你需要存储一个函数来做到这一点。

const strToType = <String, A Function(argTypes)> {
 'str1': (args) => new A(args),
 'str2': (args) => new C(args),
 'str3': (args) => new C(args),
 'str4': (args) => new D(args),
 // etc.
};

那你就可以按你的要求使用了:

A variable = strToType[someString](args);

只要所有构造函数都接受相同的参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 2015-10-29
    相关资源
    最近更新 更多