如何确定System.Type值的大小? [英] How to determine the size of a System.Type value?

查看:56
本文介绍了如何确定System.Type值的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定Type值的大小?

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

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

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

推荐答案

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

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

  • Marshal.SizeOf(t)(

  • 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)(

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

F#中的 sizeof<'T> 构造仅在类型为静态已知时起作用,但随后会生成漂亮的单个 sizeof IL指令(如您所见<来自源代码的a href ="https://github.com/fsharp/fsharp/blob/1745b5f7b19bdb285f3a9c06527b22baf01d41f9/src/fsharp/FSharp.Core/prim-types.fs#L471" rel ="noreferrer"> ).

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).

这篇关于如何确定System.Type值的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆