Skip to Content

施工中

这一篇还在编写,内容与示例随时可能变动。

反射(Reflection)

反射在运行期获取以下信息:这个值是什么类型、它有哪些成员、成员上贴了哪些特性。入口是 std::Reflect 模块 typeof(T) 语法,产出五个不可构造的句柄类型:Type、Field、Prop、Attr、Method。

当前版本反射只读为主,唯一可写面是字段读写。动态调用方法、按 Type 构造实例、给 prop 赋值、动态生成类型目前都不在反射面内。

Type:类型的句柄

typeof(T) 产出类型 T 的 Type 值,Reflect.TypeOf(v) 产出值 v 的运行期真实类型,两者在同一域,== 与 != 可互比。声明位装的是派生实例时,TypeOf 给的是派生类型:

class Base { public var a: int = 0; } class Derived : Base { public var b: int = 0; } func main() -> int { val b: Base = new Derived(); print(Reflect.TypeOf(b) == typeof(Derived), Reflect.TypeOf(b) != typeof(Base)); print(Reflect.TypeOf(42) == typeof(int)); return 0; }
True True True

TypeOf 任何值都有类型答案,不走 fail。装箱标量与静态 typeof 同键,没有成员面的可用 .Name 判别。

传入值TypeOf 结果
命名类型实例 / enum 实例该类型的 Type
装箱标量(int / float / bool / string / char)对应标量 Type
容器(list / set / map / array)域 Type:"list"、"set"、"map"、"array"
向量与颜色域 Type:"vec2" ~ "color"
有值的可空(int? 装 9)剥掉 ? 后的内层 Type
null(含空可空)域 Type:"null"
错误值 / 函数值域 Type:"error" / "function"
宿主侧未知值域 Type:"external"

Type 是一等值:存变量、当参数传、放进 list<Type> 都合法。

func AddOne(n: int) -> int { return n + 1; } func main() -> int { val xs: list<int> = [1, 2]; print(Reflect.TypeOf(xs).Name, Reflect.TypeOf(vec2(1.0, 2.0)).Name); val has: int? = 9; val none: int? = null; print(Reflect.TypeOf(has) == typeof(int), Reflect.TypeOf(none).Name); print(Reflect.TypeOf(null).Name, Reflect.TypeOf(AddOne).Name); return 0; }
list vec2 True null null function

编写到此Written up to here

本页其余部分尚未完成,内容随时补充。The rest of this page is not written yet; more content will follow.

最后更新于 2026年10月10日