【问题标题】:Dart : Read annotated value of a fieldDart:读取字段的注释值
【发布时间】: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)更容易获得枚举值,有什么建议吗?在这里使用反射之类的东西会有所帮助吗?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    在运行时访问注解的唯一方法确实是使用dart:mirrors 进行反射。该库在编译到 Web 或 Flutter 时不可用,因此它可能无法解决您的问题。

    你可以在这里做的是:

      int get value => this.index;
    

    仅当值实际上与索引相同时才有效(0 表示第一个声明的值,1 表示下一个等)

    【讨论】:

    • 是的,这很不幸。使用 index 感觉有点奇怪,因为意外的重新排序可能会搞砸。无论如何,感谢您抽出宝贵时间回答:)
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 2016-04-15
    • 2020-02-29
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多