如何检查结构消耗的字节数?如果我创建一个相对较大的结构,我如何计算它在内存中占用的字节数?我们可以手动完成,但如果结构足够大,那么我们该怎么做呢?是否有一些代码块或应用程序?
3 回答
largeQ
TA贡献2039条经验 获得超8个赞
您可以使用sizeof运算符或SizeOf函数。
这些选项之间存在一些差异,请参阅参考链接以获取更多信息。
无论如何,使用该函数的一个好方法是使用这样的泛型方法或扩展方法:
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);
}}
一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
您可以将sizeof()关键字用于不包含任何字段或属性作为引用类型的用户定义结构,也可以使用Marshal.SizeOf(Type)或Marshal.SizeOf(object)获取具有顺序或显式布局的类型或结构的非托管大小。
- 3 回答
- 0 关注
- 458 浏览
添加回答
举报
0/150
提交
取消
