Skip to Content

typeof 与 nameof

两个编译期内省表达式:typeof(T) 拿类型的 Type 值,nameof(x) 把名字折叠成字符串常量。

typeof:类型的值

typeof(T) 产出类型 T 的 Type 值,可以比较、传递、存进常量:

func main() -> int { print(typeof(int) == typeof(int), typeof(string) == typeof(int)); return 0; }
True False

同一类型产同一 Type 值,不同类型不等。Type 值的成员面、值侧映射与 Field 读写见反射;轻量的运行期类型判断也可以用 is(见 任意类型(Any))。

nameof:名字的字符串

nameof(x) 把名字折叠为字符串常量,重命名时自动跟随:

const Who: string = nameof(Answer); func Answer() -> int => 42; func main() -> int { print(nameof(Who)); return 0; }
Who
  • nameof(x) / nameof(obj.Member) / nameof(TypeName) / nameof(Mod::Sym) 都合法,折叠为名字字符串;
  • 因为是常量,可作 const 初始化器、特性实参、case 标签;
  • 拼错的名字编译期直接报未定义,比手写字符串安全。

注意

  • 仅「标识符 + (」紧邻形被拦截为 nameof 调用,其余位置的 nameof 是普通标识符;
  • typeof 的操作数必须是类型名;泛型实例化写全(typeof(list<int>));
  • nameof 是编译期折叠,产物里只有字符串常量;typeof 产出 intern 的 Type 值,同一类型恒同值。
最后更新于 2026年10月8日