鸿蒙开发TypeScript第八课:枚举enum
·
鸿蒙开发TypeScript第八课:枚举enum
枚举很少用到。
经常需要定义一组相关的常量就可以用枚举
直接上代码:
// 1、默认是数值枚举
enum MyColor {
Green, // 0
Red, // 1
Blue // 2
}
// 2、定义字符串枚举
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT',
}
// 3、使用示例
enum UserRole {
GUEST = 0,
USER = 1,
MODERATOR = 2,
ADMIN = 3,
SUPER_ADMIN = 4
}
class User {
name: string;
role: UserRole;
constructor(name: string, role: UserRole) {
this.name = name;
this.role = role;
}
hasPermission(requiredRole: UserRole): boolean {
return this.role >= requiredRole;
}
getRoleName(): string {
switch (this.role) {
case UserRole.GUEST: return "访客";
case UserRole.USER: return "普通用户";
case UserRole.MODERATOR: return "版主";
case UserRole.ADMIN: return "管理员";
case UserRole.SUPER_ADMIN: return "超级管理员";
default: return "未知";
}
}
}
@Entry
@Component
struct Lesson_8_enum_Page {
@State message: string = 'Lesson_8_enum_Page';
aboutToAppear(): void {
let c:MyColor = MyColor.Green
// 使用
let admin = new User("张三", UserRole.ADMIN);
logContent("conggeL8",admin.hasPermission(UserRole.USER)); // true
logContent("conggeL88",admin.getRoleName()); // "管理员"
}
教程项目的全部源码图:

有需要完整教程demo的私信我,我每天都看私信的。
更多推荐

所有评论(0)