方法来确定复杂对象的大小在.NET?方法来、复杂、对象、大小

2023-09-04 00:06:47 作者:有个名字叫早恋

是否有办法在确定.NET复杂对象的总大小?这个目的是由其他目的的,并且可能保持对其他复杂的对象。一些此对象封装的对象可能是POD,其他人可能不会。

Are there ways at determining the total size of a complex object in .NET? This object is composed of other objects and might hold references to other complex objects. Some of the objects encapsulated by this object might be POD, others may not.

推荐答案

你有什么是不是复杂的对象,这是一个对象图。要确定它的总规模,需要走的图形 - 开始与一些根对象,并使用反射来枚举引用类型的字段和检索它们的值(和检查循环,当然)

What you have is not a "complex object", it's an object graph. To determine its total size, you need to walk that graph - starting with some root object, and using Reflection to enumerate fields of reference types and retrieving their values (and checking for loops, of course).

要得到一个特定对象的大小在图中,参见this回答一个相关的问题,但请注意,这是一个邪恶的黑客攻击,完全不支持,可能会破坏(并且可能已经被打破),并可能导致天体批发小猫种族灭绝。也就是说,没有非哈克的方式来获得precise价值,因为它是一个实现细节的定义 - 你不应该有它的任何使用。而对于找出在调试/分析的应用程序的内存使用量的目的,黑客就足够了。

To get the size of a particular object in the graph, see this answer to a related question, but note that this is an evil hack, completely unsupported, may break (and may already be broken), and may result in a wholesale kitten genocide in heavenly spheres. That said, there is no "non-hacky" way to get a precise value, because it is an implementation detail by definition - you shouldn't have any use for it. And for the purpose of finding out the memory usage of an app during debugging/profiling, the hack is good enough.