我来自 Kotlin 背景,我习惯了 enums 实现这一事实Comparable,这允许我执行如下操作:
给定一个枚举
enum class Fruit{
APPLE,
BANANA,
ORANGE,
}
Run Code Online (Sandbox Code Playgroud)
我可以使用运算符<、或来比较此枚举的任何出现,例如>:<=>=
APPLE < BANANA -> true
ORANGE < BANANA -> false
Run Code Online (Sandbox Code Playgroud)
我想知道 dart 默认情况下是否具有相同的功能,或者我是否必须为我可能需要的任何枚举定义自定义运算符。
很容易检查Enum文档或自己尝试一下,看看Enum类是否不提供operator <、operator >等。
Dart 2.15确实添加了一个Enum.compareByIndex方法,您还可以向Enums 添加扩展方法:
extension EnumComparisonOperators<T extends Enum> on T {
bool operator <(T other) {
return index < other.index;
}
bool operator <=(T other) {
return index <= other.index;
}
bool operator >(T other) {
return index > other.index;
}
bool operator >=(T other) {
return index >= other.index;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5803 次 |
| 最近记录: |