问题
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) takesSystem.Type
as an argument and returns the size of the type that is represented by theSystem.Type
value (I believe this is what you want.)Marshal.SizeOf(structure)
(MSDN) takes anyobject
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