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);
相关推荐
用户693717500138439 分钟前
Claude Code终端日志Token占用实测:一个过滤器砍掉60%-90%
android·前端·后端
AOwhisky41 分钟前
Python 学习笔记(第十三期)——运维自动化(下·前篇):远程命令执行——paramiko基础篇
运维·python·学习·云原生·自动化·运维开发·paramiko
蝉蜕日记1 小时前
AccumuPDF高级版 v2.57 | 视图文转换PDF,合并分割压缩
android·智能手机·pdf·生活·软件需求
前端世界1 小时前
MySQL 基础入门(学习第4天)——约束与 DML 操作详解
数据库·学习·mysql
dear_bi_MyOnly1 小时前
【SpringBoot配置文件】
java·spring boot·后端·学习·spring·java-ee·学习方法
吐了啊取名字太难1 小时前
美颜系统AI修图本地跑并支持Mac、win、安卓、iOS不卡顿
android·人工智能·windows·数码相机·mac·ai编程
AOwhisky1 小时前
Python 学习笔记(第十四期)——运维自动化(下·中篇):远程文件传输——paramiko进阶篇
运维·python·学习·云原生·自动化·文件传输·paramiko
math_hongfan1 小时前
鸿蒙Flutter setState机制深入理解
学习·flutter·华为·harmonyos·鸿蒙
其实防守也摸鱼2 小时前
补天SRC新手入门指南:从0到1的漏洞挖掘之路
网络·python·学习·安全·web安全·数据挖掘·挖洞
星恒随风2 小时前
C++ STL 栈详解:stack 的使用、经典题目与简单模拟实现
开发语言·数据结构·c++·笔记·学习