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);
相关推荐
星光一影7 小时前
合成植物大战僵尸 安卓原生APP Cocos游戏 支持Sigmob
android·游戏·php·html5·web app
YuforiaCode7 小时前
黑马AI大模型神经网络与深度学习课程笔记(个人记录、仅供参考)
人工智能·笔记·深度学习
2501_915918417 小时前
iOS 项目中证书管理常见的协作问题
android·ios·小程序·https·uni-app·iphone·webview
YJlio7 小时前
ZoomIt 学习笔记(11.9):绘图模式——演示时“手写板”:标注、圈画、临时白板
服务器·笔记·学习
allk557 小时前
Android ANR 深度起底:从系统埋雷机制到全链路治理体系
android
巴拉巴拉~~7 小时前
Flutter 通用表单输入组件 CustomInputWidget:校验 + 样式 + 交互一键适配
javascript·flutter·交互
满天星83035777 小时前
【Linux】信号(下)
android·linux·运维·服务器·开发语言·性能优化
2501_915918417 小时前
提升 iOS 应用安全审核通过率的一种思路,把容易被拒的点先处理
android·安全·ios·小程序·uni-app·iphone·webview
专注于大数据技术栈7 小时前
java学习--String
java·开发语言·学习