我來自 Kotlin 背景,我習慣了 enums 實作的事實Comparable,這使我可以執行以下操作:
給定一個列舉
enum class Fruit{
APPLE,
BANANA,
ORANGE,
}
我可以使用運營商<,>,<=或者>=,比較此列舉的任何事件,如:
APPLE < BANANA -> true
ORANGE < BANANA -> false
我想知道 dart 默認情況下是否具有相同的功能,或者我是否必須為我可能需要的任何列舉定義自定義運算子。
uj5u.com熱心網友回復:
這很容易檢查Enum檔案或自己嘗試一下,看看那Enum類不提供operator <,operator >等等。
Dart 2.15 確實添加了一個Enum.compareByIndex方法,您也可以為Enums添加擴展方法:
extension EnumComparisonOperators on Enum {
bool operator <(Enum other) {
return index < other.index;
}
bool operator <=(Enum other) {
return index <= other.index;
}
bool operator >(Enum other) {
return index > other.index;
}
bool operator >=(Enum other) {
return index >= other.index;
}
}
uj5u.com熱心網友回復:
如其他評論中所述,您還可以創建自己的運算子并使用它。
試試下面的代碼,看看如何在不創建運算子的情況下處理它。
enum Fruit{
APPLE,
BANANA,
ORANGE,
}
void main() {
print(Fruit.APPLE.index == 0);
print(Fruit.BANANA.index == 1);
print(Fruit.ORANGE.index == 2);
if( Fruit.APPLE.index < Fruit.BANANA.index ){
// Write your code here
print("Example");
}
}
結果
true
true
true
Example
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/408812.html
標籤:
上一篇:SetState不更新串列視圖
