枚举类型
枚举类型,通常称为枚举(enumerations)或枚举(enums),是一种特殊的类,用于表示固定数量的常量值。
声明简单枚举
#要声明一个简单的枚举类型,请使用 enum
关键字并列出你希望枚举的值
dart
enum Color { red, green, blue }
声明增强型枚举
#Dart 还允许枚举声明定义带有字段、方法和 const 构造函数的类,这些类的实例数量限制为固定且已知的常量实例。
要声明增强型枚举,请遵循与普通类类似的语法,但需满足一些额外要求:
- 实例变量必须是
final
的,包括通过Mixin添加的变量。 - 所有生成式构造函数都必须是常量。
- 工厂构造函数只能返回一个固定的、已知的枚举实例。
- 不能扩展其他类,因为
Enum
已自动扩展。 - 不能重写
index
、hashCode
和相等运算符==
。 - 在枚举中不能声明名为
values
的成员,因为它会与自动生成的静态values
getter 冲突。 - 枚举的所有实例都必须在声明的开头声明,并且必须至少声明一个实例。
增强型枚举中的实例方法可以使用 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);