Skip to main content
文档站副本

本页为语义契约的发布副本;请在上游 ZTSTest/Docs/spec 修改后执行 npm run sync-spec。(源:marshal\08-ENUM.md

枚举 Marshal

规范性: C# enum 在 JavaScript 与 C# 之间的默认 Marshal 规则。 相关: 类型表常量 → ../02-TYPE-SYSTEM.md §3.5;zts.box../05-LIB.mdref enum → 03-BYREF.md[TsMarshalAs]02-MARSHAL-AS.md

平台原则: 枚举默认 推送 exotic,而按 number(整数) Marshal。v1 禁止 bigint 通道../00-OVERVIEW.md §1.3)。


1. 设计要点

场景形态
默认传参numberNumber.isInteger
boxed 实例ByObj exotic zts.box
类型表常量number 属性( exotic)

枚举类型对象 [[Construct]]不可 new EnumType(...) 构造 ByVal。


2. 默认规则(C# ↔ JavaScript)

方向默认形态说明
C# → JSnumber(整数)底层整数值; Push exotic
JS → C#number(整数)Enum.ToObject / 等价
JS → C#(备选)ByObj exotic(boxed)解包 underlying

不接受(除非另行标注):枚举 名字 stringboolean、plain object。

undefined:必选 enum 形参 → throwNullable<enum> 无值 → null/undefined01-OVERVIEW.md §2)。


3. 底层类型与范围

读取 enum underlying typeInt32Byte 等):

底层类型PushPop
sbyteulongnumber 整数number 整数 + 范围校验

Pop 越界 → throw Error('zts: …')

禁止 bigint Popthrow Error('zts: bigint is not supported for enum marshal')(或等价文案)。


4. 类型表常量字段

const Color = CSharp.AC['MyGame.Color'];
console.assert(Color.Red === 0); // number,非 exotic
foo(Color.Red);
foo(1); // 裸整型,须可转换为该 enum

5. Boxed 形态(zts.box

const boxed = zts.box(Color, Color.Green);
const boxed2 = zts.box(Color, 2);
说明
返回值ByObj exotic(boxed)
拆箱zts.unbox(boxed) → underlying number
ref Colorboxed 走临时槽路径(03-BYREF.md

6. ref / out / in enum

JS 实参行为
OpaqueValuehandle 地址
integer number临时槽
zts.box 产物临时槽

C#→JS:ref enum 默认 OpaqueValue


7. [TsMarshalAs] 扩展

标注by-val enum
Default§2
Object非法(by-val);回退 Default
OpaqueValueC#→JS 合法
Table / UnpackedValues非法

8. 与 struct / class 差异(摘要)

enumstructclass
默认跨边界numberByVal exoticByObj exotic
[[Construct]]
boxedzts.boxbox / ByVal构造

9. Mono / Il2Cpp 一致性

默认 Push/Pop、常量、zts.box、范围校验、bigint 拒绝 — 须一致


10. 相关文档

文档内容
01-OVERVIEW.mdnumber、禁止 bigint
03-BYREF.mdbyref
05-STRUCT.mdbox 对比
../02-TYPE-SYSTEM.md枚举类型表