蓝色天空.知识 · 实践 · 创造
我的收藏
Dart 教程目录 21章
Dart / LEARN BY DOING

Dart 枚举与符号

详解基础 enum 枚举定义与 switch 穷尽检查、增强枚举(Enhanced Enums)的字段与方法封装、Symbol 标识符对象的压缩注意事项,以及 Rune 与 UTF-16 Unicode 码点处理。

学完这一章,你能够

  • 详解基础 enum 枚举定义与 switch 穷尽检查、增强枚举(Enhanced Enums)的字段与方法封装、Symbol 标识符对象的压缩注意事项,以及 Rune 与 UTF-16 Unicode 码点处理。

基础 enum 定义与增强枚举(Enhanced Enums)

枚举(`enum`)是一种用于表达有限具名常量集合的特殊类,常用于建模订单状态、方向或颜色等离散选项。每个枚举值自动具备从 0 递增的 `.index` 序号,枚举类型提供 `.values` 常量列表与 `.byName('approved')` 按名解析方法。将枚举与 `switch` 结合使用时,Dart 编译器会检查分支是否穷尽全部枚举成员,有效防止新增状态后遗漏处理分支。

现代 Dart(自 2.17 引入并在 Dart 3.x 广泛采用)支持增强枚举(Enhanced Enums),允许枚举拥有 `final` 实例字段、计算属性 Getter、实例方法与静态辅助方法——例如 `HttpStatus` 可为每个状态常量绑定 `code` 与 `message`,并提供 `isSuccess`、`isClientError` 属性及 `HttpStatus.fromCode(int)` 静态查找器。由于枚举实例全部属于编译期常量,其成员变量必须为 `final`,构造函数必须声明为 `const`。

Symbol 标识符对象与 Rune Unicode 码点

`Symbol` 用来以不透明对象形式表示 Dart 程序中的标识符(通过 `#name` 字面量创建,例如 `#blueSky`、`#helloWorld`),支持基于身份的相等性比较并可充当 `Map` 键。日常业务极少直接使用 `Symbol`,它主要面向反射(`dart:mirrors`)与代码生成框架。需要牢记:经过压缩(minification)编译后,标识符名称可能被混淆,因此绝不能依赖 `Symbol("blueSky").toString()` 的字符串内容来编写业务逻辑。

Dart 的 `String` 底层是 UTF-16 代码单元序列,而 `Rune` 表示完整的 Unicode 码点(整型值)。对于处于基本多语言平面(BMP)之外的字符(如 Emoji 笑脸 `\u{1F600}`),它在 UTF-16 中占用 2 个代理代码单元,但通过 `text.runes` 可准确迭代其唯一码点 `U+1F600`,也可使用 `String.fromCharCode(0x2764)` 由码点反向构造字符。普通业务直接操作 `String`(或使用官方 `characters` 包按字素簇切分)即可,底层文本编辑器与排版引擎则需借助 `runes` 精确处理码点。

离线校验枚举穷尽性、增强枚举 HttpStatus、Symbol 比较及 Emoji UTF-16/Rune 码点

含完整源码 · 211 行
展开查看收起
python
"""Offline Dart 3.x semantic verification lab for Chapter 14 (enums-and-symbols)."""
import json
from enum import Enum

VERSION = "CPython 3.12.14 offline Dart 3.x semantic verifier (dart SDK absent)"


def case_basic_enum_and_exhaustiveness():
    class Status(Enum):
        pending = 0
        approved = 1
        rejected = 2
        cancelled = 3

    def by_name(name: str) -> Status:
        try:
            return Status[name]
        except KeyError as exc:
            raise ValueError(f"No enum value with name '{name}'") from exc

    labels = {
        Status.pending: "订单待处理",
        Status.approved: "订单已批准",
        Status.rejected: "订单被拒绝",
        Status.cancelled: "订单已取消",
    }
    exhaustive = set(labels.keys()) == set(Status)

    invalid_caught = False
    try:
        by_name("unknown")
    except ValueError:
        invalid_caught = True

    expected = {
        "pending_index": 0,
        "all_names": ["pending", "approved", "rejected", "cancelled"],
        "by_name_approved": "Status.approved",
        "invalid_by_name_throws": True,
        "switch_exhaustive": True,
        "pending_label": "订单待处理",
    }
    actual = {
        "pending_index": Status.pending.value,
        "all_names": [s.name for s in Status],
        "by_name_approved": f"Status.{by_name('approved').name}",
        "invalid_by_name_throws": invalid_caught,
        "switch_exhaustive": exhaustive,
        "pending_label": labels[Status.pending],
    }
    return {
        "name": "basic_enum_and_exhaustiveness",
        "summary": "校验基础 enum 的 .index、.values、.byName() 及 switch 穷尽性覆盖检查",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_enhanced_enum_fields_and_methods():
    class HttpStatus(Enum):
        ok = (200, "请求成功")
        created = (201, "资源已创建")
        badRequest = (400, "请求错误")
        unauthorized = (401, "未授权")
        notFound = (404, "资源未找到")
        serverError = (500, "服务器内部错误")

        def __init__(self, code: int, message: str):
            self.code = code
            self.message = message

        @property
        def is_success(self) -> bool:
            return 200 <= self.code < 300

        @property
        def is_client_error(self) -> bool:
            return 400 <= self.code < 500

        @property
        def is_server_error(self) -> bool:
            return self.code >= 500

        @classmethod
        def from_code(cls, code: int):
            for s in cls:
                if s.code == code:
                    return s
            return None

    st = HttpStatus.notFound
    found_201 = HttpStatus.from_code(201)
    found_999 = HttpStatus.from_code(999)

    expected = {
        "not_found_code": 404,
        "not_found_msg": "资源未找到",
        "is_success": False,
        "is_client_error": True,
        "is_server_error": False,
        "from_201": "资源已创建",
        "from_999": None,
    }
    actual = {
        "not_found_code": st.code,
        "not_found_msg": st.message,
        "is_success": st.is_success,
        "is_client_error": st.is_client_error,
        "is_server_error": st.is_server_error,
        "from_201": found_201.message if found_201 else None,
        "from_999": found_999,
    }
    return {
        "name": "enhanced_enum_fields_and_methods",
        "summary": "校验增强枚举的 final 字段、const 构造语义、实例计算属性与静态 fromCode 查找",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_symbol_equality_and_minification():
    class DartSymbol:
        def __init__(self, ident: str):
            self._ident = ident

        def __eq__(self, other) -> bool:
            return isinstance(other, DartSymbol) and self._ident == other._ident

        def __hash__(self) -> int:
            return hash(("DartSymbol", self._ident))

        def to_string(self, minified: bool = False) -> str:
            return 'Symbol("a")' if minified else f'Symbol("{self._ident}")'

    sym1 = DartSymbol("blueSky")
    sym2 = DartSymbol("helloWorld")
    sym3 = DartSymbol("blueSky")
    metadata = {DartSymbol("author"): "BlueSky", DartSymbol("version"): "1.0.0"}

    expected = {
        "sym1_eq_sym3": True,
        "sym1_eq_sym2": False,
        "map_lookup_author": "BlueSky",
        "unminified_str": 'Symbol("blueSky")',
        "minified_str_differs": True,
    }
    actual = {
        "sym1_eq_sym3": sym1 == sym3,
        "sym1_eq_sym2": sym1 == sym2,
        "map_lookup_author": metadata[DartSymbol("author")],
        "unminified_str": sym1.to_string(False),
        "minified_str_differs": sym1.to_string(False) != sym1.to_string(True),
    }
    return {
        "name": "symbol_equality_and_minification",
        "summary": "校验 Symbol 相等性、作为 Map 键以及压缩编译后 toString() 不可用于业务逻辑的注意事项",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_runes_and_unicode_code_points():
    text = "DART"
    ascii_points = [ord(ch) for ch in text]
    hex_labels = [f"{ch} -> U+{ord(ch):04X}" for ch in text]
    heart = chr(0x2764)
    smile = "\U0001F600"
    utf16_code_units = len(smile.encode("utf-16-le")) // 2
    rune_points = [f"U+{ord(ch):X}" for ch in smile]

    expected = {
        "ascii_points": [68, 65, 82, 84],
        "hex_labels": ["D -> U+0044", "A -> U+0041", "R -> U+0052", "T -> U+0054"],
        "heart_codepoint": "U+2764",
        "smile_utf16_units": 2,
        "smile_rune_count": 1,
        "smile_runes": ["U+1F600"],
    }
    actual = {
        "ascii_points": ascii_points,
        "hex_labels": hex_labels,
        "heart_codepoint": f"U+{ord(heart):04X}",
        "smile_utf16_units": utf16_code_units,
        "smile_rune_count": len(smile),
        "smile_runes": rune_points,
    }
    return {
        "name": "runes_and_unicode_code_points",
        "summary": "校验 Rune Unicode 码点提取、String.fromCharCode 与非 BMP Emoji 的 UTF-16 代理对差异",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_basic_enum_and_exhaustiveness(),
        case_enhanced_enum_fields_and_methods(),
        case_symbol_equality_and_minification(),
        case_runes_and_unicode_code_points(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
离线脚本确认 Status 枚举索引与 byName 解析、HttpStatus 增强枚举属性与 fromCode、Symbol 相等性与压缩差异,以及笑脸 Emoji 的 UTF-16 双单元与单 Rune U+1F600。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a2539.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Dart

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2539.zip

下载课程关联工程包:Dart

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a2534.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

因为 Dart 枚举的所有值都在编译阶段实例化为固定不变的编译期常量(可用于 `switch` 匹配与常量上下文),唯有 `final` 字段与 `const` 构造函数才能保证其不可变性与编译期可求值性。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习