本文介绍了如何查看我的结构占用的字节数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我创建一个相对较大的结构,我怎么能计算出字节在内存占用?
If I am creating a relatively large structure, how can I calculate the bytes it occupies in memory?
我们可以做手工,但如果结构是足够大的话,我们怎么办呢?有一些code块或应用程序?
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); } }更多推荐
如何查看我的结构占用的字节数?
发布评论