繁体   English   中英

用于创建类型变量的 Dart Factory 类

[英]Dart Factory class for creating variables with type

问题如下。 我有一个我试图在 Dart 中做的打字稿工厂类:

class FactoryClass{

  factory FactoryClass(dynamic types, String className, dynamic defaultValue){
    if(types[className] != null ){
      return types[className](defaultValue);
    }
    else{
      throw Exception("");
    }
  }
}

在 TS 中是这样使用的:

let variable= new FactoryClass([String, Number, etc...], "Number", "42")

在 TypeScript 中会返回一个值为 42 的 Number 类型变量

但是,它不会在 Dart 中工作,因为类型没有为此的构造函数。 所以我不能做类似的事情

final myString = new String("def_value")

所以问题来了,我怎样才能在飞镖中做到这一点?

你可以在 Dart 中只用函数做类似的事情:

typedef Factory = dynamic Function(dynamic value);

dynamic create(Map<String, Factory> types, String className, dynamic defaultValue) {
    if (types.containsKey(className)) {
      return types[className]!(defaultValue);
    } else {
      throw Exception("no factory for $className");
    }
  }

final factories = <String,  Factory>{
  'String': (s) => s.toString(),
  'int': (i) => i is int ? i : int.parse('$i'),
  'bool': (b) => b is bool ? b : ('$b' == 'true'),
};

show(v) => print('Value $v has type ${v.runtimeType}');

main() {
  show(create(factories, 'String', 'foo'));
  show(create(factories, 'int', '42'));
  show(create(factories, 'bool', 'false'));
}

印刷:

Value foo has type String
Value 42 has type int
Value false has type bool

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM