flutter 如何像在c++中那样给dart枚举赋值

iezvtpos  于 2023-01-14  发布在  Flutter
关注(0)|答案(1)|浏览(296)

我试图使c++适应dart,在使用枚举时遇到了这种情况,即赋值默认值 我想是的。遵守规则

enum skills_t : uint8_t {
    SKILL_FIST = 0,
    SKILL_CLUB = 1,
    SKILL_SWORD = 2,
    SKILL_AXE = 3,
    SKILL_DISTANCE = 4,
    SKILL_SHIELD = 5,
    SKILL_FISHING = 6,
    SKILL_CRITICAL_HIT_CHANCE = 7,
    SKILL_CRITICAL_HIT_DAMAGE = 8,
    SKILL_LIFE_LEECH_CHANCE = 9,
    SKILL_LIFE_LEECH_AMOUNT = 10,
    SKILL_MANA_LEECH_CHANCE = 11,
    SKILL_MANA_LEECH_AMOUNT = 12,

    SKILL_MAGLEVEL = 13,
    SKILL_LEVEL = 14,

    SKILL_FIRST = SKILL_FIST,
    SKILL_LAST = SKILL_MANA_LEECH_AMOUNT
};

}
uint32_t skillBase[SKILL_LAST + 1] = {50, 50, 50, 50, 30, 100, 20};

是否可以将此代码修改为dart/flutter?我想在dart中重复相同的操作,似乎他分配了这些值 范围内的每个枚举

wgxvkvu9

wgxvkvu91#

是的,可以将此代码修改为** dart /Flutter。**
在Dart中,可以使用enum关键字定义枚举。语法类似于C++,,但不需要指定类似uint8_t的类型。
关于默认值,您可以像在C中那样用一个值初始化枚举成员。
下面是一个C
代码如何适应**Dart:**的示例

enum Skills {
  FIST,
  CLUB,
  SWORD,
  AXE,
  DISTANCE,
  SHIELD,
  FISHING,
  CRITICAL_HIT_CHANCE,
  CRITICAL_HIT_DAMAGE,
  LIFE_LEECH_CHANCE,
  LIFE_LEECH_AMOUNT,
  MANA_LEECH_CHANCE,
  MANA_LEECH_AMOUNT,
  MAGLEVEL,
  LEVEL,
  FIRST = FIST,
  LAST = MANA_LEECH_AMOUNT,
}

final List<int> skillBase = [
  50, 50, 50, 50, 30, 100, 20
];

还可以使用Map将默认值分配给每个枚举成员。

enum Skills {
  FIST,
  CLUB,
  SWORD,
  AXE,
  DISTANCE,
  SHIELD,
  FISHING,
  CRITICAL_HIT_CHANCE,
  CRITICAL_HIT_DAMAGE,
  LIFE_LEECH_CHANCE,
  LIFE_LEECH_AMOUNT,
  MANA_LEECH_CHANCE,
  MANA_LEECH_AMOUNT,
  MAGLEVEL,
  LEVEL,
  FIRST = FIST,
  LAST = MANA_LEECH_AMOUNT,
}

final Map<Skills, int> skillBase = {
  Skills.FIST: 50,
  Skills.CLUB: 50,
  Skills.SWORD: 50,
  Skills.AXE: 50,
  Skills.DISTANCE: 30,
  Skills.SHIELD: 100,
  Skills.FISHING: 20,
  // Add the rest of the skills
};

上述两个例子在落镖/Flutter中都能很好地工作。

相关问题