如何查看我的结构占用的字节数?

编程入门 行业动态 更新时间:2024-10-26 16:25:05
本文介绍了如何查看我的结构占用的字节数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我创建一个相对较大的结构,我怎么能计算出字节在内存占用?

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); } }

更多推荐

如何查看我的结构占用的字节数?

本文发布于:2023-11-02 15:12:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552731.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字节   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!