【问题标题】:Use Enum.values in with generic class in dart将 Enum.values 与 dart 中的泛型类一起使用
【发布时间】:2022-12-18 18:12:16
【问题描述】:

这个问题是九年前针对 javascript 提出的,但我找不到 dart 的答案。我尝试用枚举实现 json 序列化。有一些库的解决方案,但我想回答飞镖逻辑。

enum GenderType{
  Male,
  Female,
  NonBinary
}
T? getEnum<T>(String key) {
     return (T as Enum).values[_pref?.getInt(key)];
}

我想这样写。虽然我可以调用 GenderType.values,但我不能将它们称为 T.values。

【问题讨论】:

标签: flutter dart generics enums


【解决方案1】:

你不能这样做。首先Enum 类不包含values 列表。第二个原因是枚举中的 values 是一个静态字段,即使将它们转换为特定类型,也不能调用泛型上的静态方法或字段。

如果你想创建T? getEnum&lt;T&gt;(String key),你可以做到这一点,但在坏方法.所以这只是一个例子:

T? getEnum<T>(String key) {
  if(T == GenderType) {
    //needs some additional checks if _pref is null or getInt(key) returned null
    return GenderType.values[_pref?.getInt(key)] as T;
  }

  //if(T == anotherType) {}
  //and so on

  throw Exception("Unhandled type: $T");
}

但最好为每种类型使用单独的方法。

【讨论】:

  • 它不是通用类型。我不想在 getEnum 函数中使用 GenderType。因为有很多不同的枚举类,比如 GenderType 并且它不能像这个代码块一样重用
猜你喜欢
  • 1970-01-01
  • 2015-09-12
  • 2010-09-08
  • 2011-07-24
  • 2020-02-29
  • 2014-08-06
相关资源
最近更新 更多