在.NET中一般都是通过sizeof()或Marshal.SizeOf()来获取数据类型的大小,来简要地看一下它们二者有何不同。

sizeof()

sizeof()在MSDN中的介绍是,在编译时获得一个数据类型的确定大小,并且被指定为一个常量。如果试图把它用在无效类型上则会出现编译错误,见CS0233

也就意味着在运行阶段它是没有开销的。

例子

 sizeof(int)

编译成IL则为:

ldc.i4.4 

Marshal.SizeOf()

在System.Runtime.InteropServices.Marshal.SizeOf(),MSDN介绍是,总是在运行时计算结构化数据类型的大小。

这就是说,像装箱或者计算大小的开销在该方法被调用时。

例子

Marshal.SizeOf<int>()

编译成IL则为:

call        System.Runtime.InteropServices.Marshal.SizeOf<Int32>

一窥究竟

我们可以看看源码 (referencesource)

 //====================================================================
// SizeOf()
//====================================================================
[ResourceExposure(ResourceScope.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public static int SizeOf(Object structure)
{
if (structure == null)
throw new ArgumentNullException("structure");
// we never had a check for generics here
Contract.EndContractBlock(); return SizeOfHelper(structure.GetType(), true);
} public static int SizeOf<T>(T structure)
{
return SizeOf((object)structure);
} [ResourceExposure(ResourceScope.None)]
[Pure]
public static int SizeOf(Type t)
{
if (t == null)
throw new ArgumentNullException("t");
if (!(t is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "t");
if (t.IsGenericType)
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), "t");
Contract.EndContractBlock(); return SizeOfHelper(t, true);
} public static int SizeOf<T>()
{
return SizeOf(typeof(T));
} [ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable);

从上面可以看出这个Marshal.SizeOf()方法依赖SizeOfHelper这个外部方法的引用,如果数据类型有提供则在外部执行计算。如果是结构体装箱为对象,则把该对象当参数传入。

注意事项

如下Marshal.SizeOf<T>() 与sizeof(T)的一些类型,计算出大小的结果

 Marshal.SizeOf<Boolean>():
sizeof(Boolean):
Marshal.SizeOf<Char>():
sizeof(Char):

看这些相同类型下,在.Net中被封送处理成非托管的数据类型时,原托管类型2个字节的Char计算成了Windows系统类型中的1个字节的SBYTE,而托管类型1个字节的Boolean计算成了Windows系统类型中的4个字节的BOOL。

(原文引自:sizeof() vs Marshal.SizeOf()

最新文章

  1. CentOS 安装 Zend Guard Loader
  2. DOM之表格与表单基础分享
  3. 自己动手编译hadoop-2.5.2源码
  4. php中urlencode与rawurlencode的区别有那些呢
  5. Mysql复制表格
  6. CSS实例:鼠标滑过超级链接文字时改变背景颜色
  7. VPS技术介绍以及分析
  8. python 中range与xrange的区别
  9. Unity Diffuse Metal Shader Mod
  10. 关于Python网络爬虫实战笔记③
  11. 使用Html5的DeviceOrientation特性实现摇一摇功能
  12. [转]C#自定义开关按钮控件--附带第一个私活项目截图
  13. python django模型内部类meta详细解释
  14. Mysql:查用的基本操作
  15. pip install beautifulsoup4.失败
  16. 使用Axure做验证码之获取验证码(一)
  17. H - An Easy Problem?!
  18. Ubuntu 16.04下添加新用户
  19. 揭开Future的神秘面纱——任务取消
  20. [OpenCV] Samples 15: Background Subtraction and Gaussian mixture models

热门文章

  1. GCC基础知识学习
  2. leetcode - [4]Sort List
  3. (概率 01背包) Just another Robbery -- LightOJ -- 1079
  4. 当有多个form表单请求时如何处理?
  5. browsersync
  6. Android之TextView灵活使用
  7. Cerebro_变量名搜索插件
  8. [ASE][Daily Scrum]11.06
  9. Windows核心编程:第4章 进程
  10. 自定义Chrome缩放比例