如何检查结构消耗的字节数? [英] How do I check the number of bytes consumed by a structure?

查看:78
本文介绍了如何检查结构消耗的字节数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我要创建一个相对较大的结构,我该如何计算它在内存中占用的字节?

If I am creating a relatively large structure, how can I calculate the bytes it occupies in memory?

我们可以手动执行,但是如果结构很大那么我们该怎么做呢?是否有一些代码块或应用程序?

We can do it manually, but if the struct is large enough then how do we do it? Is there some code chunk or application?

推荐答案

您可以使用 sizeof 运算符或 SizeOf 函数。

这些选项之间有一些差异,请参见参考链接。

You can use either the sizeof operator or SizeOf function.
There are some differences between those options, see the reference links for more.

无论如何,使用该函数的一种好方法是使用通用方法或扩展方法如下:

Anyway a good way to use that function is to have a generic method or extension method like these:

static class Test
{
  static void Main()
  {
    //This will return the memory usage size for type Int32:
    int size = SizeOf<Int32>();

    //This will return the memory usage size of the variable 'size':
    //Both lines are basically equal, the first one makes use of ex. methods
    size = size.GetSize();
    size = GetSize(size);
  }

  public static int SizeOf<T>()
  {
    return System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
  }

  public static int GetSize(this object obj)
  {
    return System.Runtime.InteropServices.Marshal.SizeOf(obj);
  }
}

这篇关于如何检查结构消耗的字节数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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