如何在飞镖中编写枚举工厂?
How to write an enum factory in dart?
我有这个枚举:
/// Firmware update BLE OTA transfert speed
enum FirmwareUpdateBleOtaTransfertSpeed { fast, medium, moderate }
具有以下扩展名:
extension FirmwareUpdateBleOtaTransfertSpeedExtension
on FirmwareUpdateBleOtaTransfertSpeed {
static FirmwareUpdateBleOtaTransfertSpeed fromSliderIndex(double value) {
if (value > 66)
return FirmwareUpdateBleOtaTransfertSpeed.fast;
else if (value > 33)
return FirmwareUpdateBleOtaTransfertSpeed.medium;
else
return FirmwareUpdateBleOtaTransfertSpeed.moderate;
}
}
我想按如下方式使用我的工厂:
speed = FirmwareUpdateBleOtaTransfertSpeed
.fromSliderIndex(value);
但是编译不通过。我必须使用如下扩展名称:
speed = FirmwareUpdateBleOtaTransfertSpeedExtension
.fromSliderIndex(value);
如何直接使用枚举 class 来生成正确的枚举?
如果你想在你的枚举上调用静态方法,你需要直接在枚举本身而不是在扩展中定义静态方法。
enum FirmwareUpdateBleOtaTransfertSpeed {
fast,
medium,
moderate;
static FirmwareUpdateBleOtaTransfertSpeed fromSliderIndex(double value) {
if (value > 66)
return FirmwareUpdateBleOtaTransfertSpeed.fast;
else if (value > 33)
return FirmwareUpdateBleOtaTransfertSpeed.medium;
else
return FirmwareUpdateBleOtaTransfertSpeed.moderate;
}
}
您还可以定义为实际的工厂构造函数:
enum FirmwareUpdateBleOtaTransfertSpeed {
fast,
medium,
moderate;
factory FirmwareUpdateBleOtaTransfertSpeed.fromSliderIndex(double value) {
if (value > 66)
return FirmwareUpdateBleOtaTransfertSpeed.fast;
else if (value > 33)
return FirmwareUpdateBleOtaTransfertSpeed.medium;
else
return FirmwareUpdateBleOtaTransfertSpeed.moderate;
}
}
请注意,您必须使用 dart 2.17 或更高版本才能使用增强的枚举功能。
我有这个枚举:
/// Firmware update BLE OTA transfert speed
enum FirmwareUpdateBleOtaTransfertSpeed { fast, medium, moderate }
具有以下扩展名:
extension FirmwareUpdateBleOtaTransfertSpeedExtension
on FirmwareUpdateBleOtaTransfertSpeed {
static FirmwareUpdateBleOtaTransfertSpeed fromSliderIndex(double value) {
if (value > 66)
return FirmwareUpdateBleOtaTransfertSpeed.fast;
else if (value > 33)
return FirmwareUpdateBleOtaTransfertSpeed.medium;
else
return FirmwareUpdateBleOtaTransfertSpeed.moderate;
}
}
我想按如下方式使用我的工厂:
speed = FirmwareUpdateBleOtaTransfertSpeed
.fromSliderIndex(value);
但是编译不通过。我必须使用如下扩展名称:
speed = FirmwareUpdateBleOtaTransfertSpeedExtension
.fromSliderIndex(value);
如何直接使用枚举 class 来生成正确的枚举?
如果你想在你的枚举上调用静态方法,你需要直接在枚举本身而不是在扩展中定义静态方法。
enum FirmwareUpdateBleOtaTransfertSpeed {
fast,
medium,
moderate;
static FirmwareUpdateBleOtaTransfertSpeed fromSliderIndex(double value) {
if (value > 66)
return FirmwareUpdateBleOtaTransfertSpeed.fast;
else if (value > 33)
return FirmwareUpdateBleOtaTransfertSpeed.medium;
else
return FirmwareUpdateBleOtaTransfertSpeed.moderate;
}
}
您还可以定义为实际的工厂构造函数:
enum FirmwareUpdateBleOtaTransfertSpeed {
fast,
medium,
moderate;
factory FirmwareUpdateBleOtaTransfertSpeed.fromSliderIndex(double value) {
if (value > 66)
return FirmwareUpdateBleOtaTransfertSpeed.fast;
else if (value > 33)
return FirmwareUpdateBleOtaTransfertSpeed.medium;
else
return FirmwareUpdateBleOtaTransfertSpeed.moderate;
}
}
请注意,您必须使用 dart 2.17 或更高版本才能使用增强的枚举功能。