我定义了一个枚举:
enum TestEnum {
test1,
test2,
}
我想用索引创建一个枚举:
E buildEnum<E extends ?????????????????>(int index) {
try {
return E.values[index];
}
catch(e) {
return null;
}
}
我不知道枚举(enum)的类型。
我定义了一个枚举:
enum TestEnum {
test1,
test2,
}
我想用索引创建一个枚举:
E buildEnum<E extends ?????????????????>(int index) {
try {
return E.values[index];
}
catch(e) {
return null;
}
}
我不知道枚举(enum)的类型。
enum A { a0, a1, a2 }
A.values[index]
// e.g: A.values[0] == A.a0
// In Dart, arrays start at 0. A.values is a regular array, so naturally, its index starts at 0.
你不能在类型参数上进行静态访问,因此这是行不通的。
除了反射(dart:mirrors
)之外,没有其他方法可以从值转到其类型的静态成员。
我知道你的意思,但似乎不被支持。至少你可以覆盖它:
enum YourEnum { a1, a2, a3 }
enum AnotherEnum { b1, b2, b3 }
abstract class ToolsEnum<T> {
T getEnumFromString(String value);
}
class YourClass with ToolsEnum<YourEnum> {
@override
YourEnum getEnumFromString(String value) {
return YourEnum.values
.firstWhere((e) => e.toString() == "YourEnum." + value);
}
}
class AnotherClass with ToolsEnum<AnotherEnum> {
@override
AnotherEnum getEnumFromString(String value) {
return AnotherEnum.values
.firstWhere((e) => e.toString() == "AnotherEnum." + value);
}
}
我知道这是一个老问题,目前至少似乎无法返回泛型 enum
中的 E
,但我正在使用以下代码:
static dynamic asEnumValue(List<dynamic> enumValues, int index) {
try {
return enumValues[index];
} catch (err) {
return null;
}
}
这样做可以避免每次都检查index
是否是枚举类型的正确值。
如果传递了正确的值,您仍然可以使用枚举属性,例如其索引。
当然,如果您没有传递正确的枚举值,您将会收到一个TypeError
。
使用示例(DartPad):
enum Test {
a,
b,
c
}
dynamic asEnumValue(List<dynamic> enumValues, int index) {
try {
return enumValues[index];
} catch (err) {
return null;
}
}
Test aTest;
Test nullTest1;
Test nullTest2;
void main() {
aTest = asEnumValue(Test.values, 0);
nullTest1 = asEnumValue(Test.values, -1);
nullTest2 = asEnumValue(Test.values, null);
print(aTest);
print(nullTest1);
print(nullTest2);
print(aTest?.index);
print(nullTest1?.index);
print(nullTest2?.index);
}
输出:
Test.a
null
null
0
null
null
enum My {a, b, c}
并添加一个扩展类
extension MyExt on My {
@overrride
int get index {
if(this == SS.a)
return 1;
else if(this == SS.b)
return 2
else return 3;
}
}