如何确定 System.Type 值的大小?

And*_*ich 5 f#

如何确定 Type 值的大小?

let typ = if true then (123).GetType() else "asdf".GetType();;
let sz = sizeof<typ>

  let sz = sizeof<typ>;;
  ----------------^^^
error FS0039
Run Code Online (Sandbox Code Playgroud)

一种解决方案是使用 Marshal.SizeOf(obj),但可能存在另一种解决方案?

Tom*_*cek 5

我认为Marshal.SizeOf这就是你在这里寻找的东西。请注意,该方法有两个重载。

  • Marshal.SizeOf(t)( MSDN )System.Type作为参数并返回由System.Type值表示的类型的大小(我相信这就是您想要的。)

  • Marshal.SizeOf(structure)( MSDN ) 接受 anyobject并根据运行时类型返回结构的大小。

sizeof<'T>F# 中的构造仅在静态知道类型时才起作用,但随后它会生成漂亮的单个sizeofIL 指令(如您从源代码中所见)。


Joh*_*mer 0

这将获取类型变量的大小:

sizeof<System.Type>
Run Code Online (Sandbox Code Playgroud)

提示是里面的任何东西都< ... >需要是类型,而不是变量。