【发布时间】:2020-03-26 22:16:35
【问题描述】:
我有一个如下所示的 Dart 枚举:
enum Gender {
@JsonValue(0)
male,
@JsonValue(1)
female,
}
我创建了一个返回字符串名称和 int 值的 dart 扩展。它看起来像这样 -
extension GenderExtention on Gender {
String get name {
switch (this) {
default:
return _getDefaultName(this);
}
}
//For the enum male, it returns "Male"
String _getDefaultName(Community value) {
if (value == null) {
return null;
}
String valueStr = value.toString();
String enumName = valueStr.substring(valueStr.indexOf('.') + 1);
return enumName[0].toUpperCase() + enumName.substring(1);
}
int get value {
switch (this) {
case Gender.male:
return 0;
case Gender.female:
return 1;
default:
return null;
}
}
}
这对于较大的枚举来说变得很痛苦,尤其是值部分。
关于如何比在扩展中手动定义枚举值(@JsonValue(0) 为 0)更容易获得枚举值,有什么建议吗?在这里使用反射之类的东西会有所帮助吗?
【问题讨论】: