How to determine the size of a System.Type value?

a 夏天 提交于 2021-01-27 07:56:20

问题


How to determine the size of a Type value?

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

  let sz = sizeof<typ>;;
  ----------------^^^
error FS0039

One solution is to use Marshal.SizeOf(obj), but may be another solution exists?


回答1:


I think Marshal.SizeOf is what you are looking for here. Note that there are two overloads of the method.

  • Marshal.SizeOf(t) (MSDN) takes System.Type as an argument and returns the size of the type that is represented by the System.Type value (I believe this is what you want.)

  • Marshal.SizeOf(structure) (MSDN) takes any object and returns the size of the structure based on the runtime type.

The sizeof<'T> construct in F# works only when the type is statically know, but then it generates nice single sizeof IL instruction (as you can see from the source code).




回答2:


This will get the size of a type variable:

sizeof<System.Type>

The hint is that anything inside < ... > needs to be a type, not a variable.



来源:https://stackoverflow.com/questions/22547082/how-to-determine-the-size-of-a-system-type-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!