Android学Dart学习笔记第二十节 类-枚举

枚举类型,通常称为枚举或枚举,是一种特殊的类,用于表示固定数量的常量值。

定义一个简单的枚举

关键字都是一样的

dart 复制代码
enum Color { red, green, blue }

可以以,结尾以便利于复制,而不会产生问题

dart 复制代码
enum Color { red, green, blue ,}

void main() {
  print(Color.values.length);//3
}

定义一个增强枚举

Dart还允许enum声明使用字段、方法和const构造函数来声明类,这些构造函数限制为固定数量的已知常量实例。

声明增强型枚举时,遵循与普通类类似的语法,但有一些额外要求:

实例变量必须是 final,包括由 mixin 添加的变量

所有生成式构造函数必须是 const

工厂构造函数只能返回固定的、已知的枚举实例之一

不能继承其他类,因为 Enum 会自动被继承

不能重写 index、hashCode 或相等运算符 ==

不能在枚举中声明名为 values 的成员,因为它会与自动生成的静态 values getter 冲突

枚举的所有实例必须在声明开头声明,并且必须至少声明一个实例

增强枚举中的实例方法可以使用this来引用当前枚举值。

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;
}

增强枚举最低要求2.17的语言版本

如何使用枚举

枚举的访问也和java一样

dart 复制代码
final favoriteColor = Color.blue;
if (favoriteColor == Color.blue) {
  print('Your favorite color is blue!');
}

每个枚举都有下标值,也是从0开始

dart 复制代码
assert(Color.red.index == 0);
assert(Color.green.index == 1);
assert(Color.blue.index == 2);

要获取所有枚举值的列表,请使用.value

dart 复制代码
List<Color> colors = Color.values;
assert(colors[2] == Color.blue);

你可以在switch中使用枚举,如果你没有考虑到所有的分支

,将会报错,你也可以使用default或者case _,

如果你对switch还不了解,可以看看之前的文章 dart 分支

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'
}

如果您需要访问枚举值的名称,可以使用.name

dart 复制代码
print(Color.blue.name); // 'blue'

你同样可以访问枚举对象的成员,和访问对象一样

dart 复制代码
print(Vehicle.car.carbonFootprint);
相关推荐
小白郭莫搞科技18 小时前
鸿蒙跨端框架Flutter学习:CustomTween自定义Tween详解
学习·flutter·harmonyos
mocoding18 小时前
使用鸿蒙化flutter_fluttertoast替换Flutter原有的SnackBar提示弹窗
flutter·华为·harmonyos
感谢地心引力18 小时前
安卓、苹果手机无线投屏到Windows
android·windows·ios·智能手机·安卓·苹果·投屏
阳光九叶草LXGZXJ19 小时前
达梦数据库-学习-47-DmDrs控制台命令(LSN、启停、装载)
linux·运维·数据库·sql·学习
2501_9481201519 小时前
基于Flutter的跨平台社交APP开发
flutter
向哆哆20 小时前
构建健康档案管理系统:Flutter × OpenHarmony 跨端实现就医记录展示
flutter·开源·鸿蒙·openharmony·开源鸿蒙
A9better20 小时前
嵌入式开发学习日志53——互斥量
stm32·嵌入式硬件·学习
进阶小白猿21 小时前
Java技术八股学习Day30
java·开发语言·学习
近津薪荼21 小时前
优选算法——双指针6(单调性)
c++·学习·算法
2601_9498683621 小时前
Flutter for OpenHarmony 电子合同签署App实战 - 主入口实现
开发语言·javascript·flutter