Dart Factory类,用于创建具有类型的变量



问题如下:我有一个打字脚本工厂类,我试图在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中进行呢?

您可以在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

最新更新