在C#中的字节查找对象实例的大小 [英] Find size of object instance in bytes in c#

查看:108
本文介绍了在C#中的字节查找对象实例的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关任意实例(对象的不同,组合物,单一对象等的集合)

For any arbitrary instance (collections of different objects, compositions, single objects, etc)

我怎么能确定其大小以字节为单位?

How can I determine its size in bytes?

(我目前得到的各种对象的集合,我试图确定它的聚集大小)

(I've currently got a collection of various objects and i'm trying to determine the aggregated size of it)

编辑:已经有人写对象的扩展方法,可以做到这一点?这会是pretty整齐海事组织。

Has someone written an extension method for Object that could do this? That'd be pretty neat imo.

推荐答案

首先,警告:接下来严格是丑陋的,无证黑客的境界。不要依赖这个工作 - 即使它现在为你的作品,它可能会停止工作,明天,任何或大或小的.NET更新

First of all, a warning: what follows is strictly in the realm of ugly, undocumented hacks. Do not rely on this working - even if it works for you now, it may stop working tomorrow, with any minor or major .NET update.

您可以使用这篇文章CLR内部 - 上次我检查,它仍然适用。这里是如何做到这一点(它通过类型句柄检索类型的内部基本实例大小字段)。

You can use the information in this article on CLR internals - last I checked, it was still applicable. Here's how this is done (it retrieves the internal "Basic Instance Size" field via TypeHandle of the type).

object obj = new List<int>(); // whatever you want to get the size of
RuntimeTypeHandle th = obj.GetType().TypeHandle;
int size = *(*(int**)&th + 1);
Console.WriteLine(size);

这适用于3.5 SP1 32位。我不知道如果字段大小,在64位是相同的 - 你可能有,如果他们不调整类型和/或偏移

This works on 3.5 SP1 32-bit. I'm not sure if field sizes are the same on 64-bit - you might have to adjust the types and/or offsets if they are not.

这将为所有正常的类型,所有实例都具有相同的,定义良好的工作类型。对于那些其这不是真的是肯定的数组和字符串,我相信也的StringBuilder 。对他们来说,你必须添加所有的大小,包含的元素,以它们的基础实例的大小。

This will work for all "normal" types, for which all instances have the same, well-defined types. Those for which this isn't true are arrays and strings for sure, and I believe also StringBuilder. For them you'll have add the size of all contained elements to their base instance size.

这篇关于在C#中的字节查找对象实例的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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