在 Dart 中,枚举类型 是一类特殊的类,用于表示固定数量的常量值。
所有枚举都会自动继承自 Enum 类,并且是密封的:不能被继承、实现、混入,也无法显式实例化。虽然抽象类与混入可以显式实现或继承 Enum,但除非被某个枚举实现或混入,否则无法真正实例化该类型的对象。
1. 简单枚举
1.1 声明简单枚举
使用 enum 关键字并列出需要枚举的值,即可声明一个简单枚举:
enum Color { red, green, blue }1.2 使用简单枚举
可以像访问普通静态变量一样使用枚举值:
final favoriteColor = Color.blue;
if (favoriteColor == Color.blue) {
print('Your favorite color is blue!');
}枚举中的每个值都有 index 属性,返回其在枚举声明中从0开始的位置:
assert(Color.red.index == 0);
assert(Color.green.index == 1);
assert(Color.blue.index == 2);使用枚举的静态常量 values 获取所有枚举值的列表:
List<Color> colors = Color.values;
assert(colors[2] == Color.blue);使用 name 属性获取枚举值的名称:
print(Color.blue.name); // 'blue'2. 增强枚举
Dart 还支持声明增强枚举,可定义包含字段、方法和常量构造函数的枚举类,其实例仅限于固定数量且已知的常量实例。
2.1 声明增强枚举
声明增强枚举的语法与普通类相似,但需满足以下约束条件:
- 实例变量必须是
final(包括通过混入添加的变量); - 所有生成式构造函数必须标记为
const; - 工厂构造函数只能返回固定的已知枚举实例;
- 无法继承其他类,因为已自动继承
Enum; - 不允许重写
index、hashCode以及相等运算符==; - 不可声明名为
values的成员,因为会与内置的静态values冲突; - 所有枚举实例必须在声明开头定义,且至少声明一个实例。
增强枚举中的实例方法可通过 this 引用当前枚举值,下面是一个带多个实例、实例变量、getter 并实现接口的增强枚举:
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;
}2.2 使用增强枚举
使用方式和普通枚举相同,另外也可以像访问普通对象成员一样访问枚举值的成员:
print(Vehicle.car.carbonFootprint); 相关推荐
- Dart 语法要点(3) —— 类和对象 2025-09-20
- Dart 语法要点(2) —— 函数 2025-09-15
- Dart 语法要点(1) —— 注释、变量、常量、数据类型 2025-09-14
- Dart 开发环境搭建 2025-09-12
评论0
暂时没有评论