Dart 语言中的类与面向对象编程特性详解
1. 枚举类型(Enum Type)
枚举类型是大多数语言中用于表示一组有限常量值的常见类型,在 Dart 中也不例外。通过使用 enum 关键字,后面跟上常量值,就可以定义一个枚举类型。例如:
enum PersonType {
student, employee
}
这里只定义了值的名称。枚举类型是一种特殊类型,具有一组有限的值,每个值都有一个 index 属性来表示其位置。下面是一个使用枚举类型的完整示例:
class Person {
PersonType type;
}
void main() {
print(PersonType.values); // 输出 [PersonType.student, PersonType.employee]
Person somePerson = new Person();
somePerson.type = PersonType.employee;
print(somePerson.type); // 输出 PersonType.employee
print(somePerson.type.index); // 输出 1
}
可以看到, index 属性是基于值的声明位置从 0 开始计数的。同时, values 是枚举类型的一个静态成员,它返回一
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



