列舉型別
列舉型別,通常稱為列舉(enumerations)或列舉(enums),是一種特殊的類,用於表示固定數量的常量值。
宣告簡單列舉
#要宣告一個簡單的列舉型別,請使用 enum 關鍵字並列出你希望列舉的值
dart
enum Color { red, green, blue }宣告增強型列舉
#Dart 還允許列舉宣告定義帶有欄位、方法和 const 建構函式的類,這些類的例項數量限制為固定且已知的常量例項。
要宣告增強型列舉,請遵循與普通類類似的語法,但需滿足一些額外要求:
- 例項變數必須是
final的,包括透過Mixin新增的變數。 - 所有生成式建構函式都必須是常量。
- 工廠建構函式只能返回一個固定的、已知的列舉例項。
- 不能擴充套件其他類,因為
Enum已自動擴充套件。 - 不能重寫
index、hashCode和相等運算子==。 - 在列舉中不能宣告名為
values的成員,因為它會與自動生成的靜態valuesgetter 衝突。 - 列舉的所有例項都必須在宣告的開頭宣告,並且必須至少宣告一個例項。
增強型列舉中的例項方法可以使用 this 引用當前列舉值。
這是一個示例,展示瞭如何宣告一個帶有多個例項、例項變數、getter 和已實現介面的增強型列舉。
dart
enum Vehicle implements Comparable<Vehicle> {
car(tires: 4, passengers: 5, carbonPerKilometer: 400),
bus(tires: 6, passengers: 50, carbonPerKilometer: 800),
bicycle(tires: 2, passengers: 1, carbonPerKilometer: 0);
const Vehicle({
required this.tires,
required this.passengers,
required this.carbonPerKilometer,
});
final int tires;
final int passengers;
final int carbonPerKilometer;
int get carbonFootprint => (carbonPerKilometer / passengers).round();
bool get isTwoWheeled => this == Vehicle.bicycle;
@override
int compareTo(Vehicle other) => carbonFootprint - other.carbonFootprint;
}使用列舉
#像訪問任何其他靜態變數一樣訪問列舉值。
dart
final favoriteColor = Color.blue;
if (favoriteColor == Color.blue) {
print('Your favorite color is blue!');
}列舉中的每個值都有一個 index getter,它返回該值在列舉宣告中的零基位置。例如,第一個值的索引為 0,第二個值的索引為 1。
dart
assert(Color.red.index == 0);
assert(Color.green.index == 1);
assert(Color.blue.index == 2);要獲取所有列舉值的列表,請使用列舉的 values 常量。
dart
List<Color> colors = Color.values;
assert(colors[2] == Color.blue);你可以在switch 語句中使用列舉,如果你沒有處理列舉的所有值,將會收到警告。
dart
var aColor = Color.blue;
switch (aColor) {
case Color.red:
print('Red as roses!');
case Color.green:
print('Green as grass!');
default: // Without this, you see a WARNING.
print(aColor); // 'Color.blue'
}如果你需要訪問列舉值的名稱,例如從 Color.blue 獲取 'blue',請使用 .name 屬性。
dart
print(Color.blue.name); // 'blue'你可以像訪問普通物件的成員一樣訪問列舉值的成員。
dart
print(Vehicle.car.carbonFootprint);