在 dart 中将 Enum.values 与泛型类一起使用

Umu*_*ALI 7 generics enums dart flutter

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

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

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

Eug*_*nko 1

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

你必须像这样改变你的功能:

T? getEnum<T>(List<T> values, String key) {
  //needs some additional checks if _pref is null or getInt(key) returned null
  return values[_pref?.getInt(key)];
}
Run Code Online (Sandbox Code Playgroud)

然后这样称呼它:

GenderType? result = getEnum(GenderType.values, "some_key");
Run Code Online (Sandbox Code Playgroud)

如果你想创造,T? getEnum<T>(String key)你可以实现这一点,但方式很糟糕。所以这只是一个例子:

T? getEnum<T>(List<T> values, String key) {
  //needs some additional checks if _pref is null or getInt(key) returned null
  return values[_pref?.getInt(key)];
}
Run Code Online (Sandbox Code Playgroud)

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

  • 它不是通用类型。我不想在 getEnum 函数中使用 GenderType。因为有很多不同的枚举类,例如 GenderType,并且它不能像此代码块一样可重用 (3认同)