简体   繁体   English

如何确定对象的大小,C#?

[英]How to determine size of an object, c#?

I have the following class: 我有以下课程:

public class MyClass
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public double Amount { get; set; }
    } 

When I try to find out size of this class on a 64 bit system by using WinDbg I get the size 40 which I am not able to understand, as far as I have read MyClass should have 当我尝试使用WinDbg在64位系统上查找此类的大小时,据我所读的MyClass应该知道,我得到的大小是40我无法理解。

8 bytes for SyncBlock
8 bytes for TypeHandle
8 bytes for string reference
4 bytes for Int32
8 bytes for double

= 36 bytes

I don't have 10 reputation that's why i am not able to post image. 我没有10个声誉,所以我无法发布图片。 Anyone has any idea why WinDbg is showing 4 extra bytes ? 任何人都知道为什么WinDbg显示4个额外的字节吗?

I believe what you're seeing is the effect of things needing to align to 8 byte boundaries in 64 bit builds (and 4 byte boundaries in 32 bit builds). 我相信您所看到的是在64位版本中需要对齐8字节边界(在32位版本中需要对齐4字节边界)的影响。 40 is the closest size >= 36 that is on an 8 byte boundary. 40是最接近的大小> = 36,位于8字节边界上。 These links talk about object size: 这些链接讨论对象大小:

Of Memory and strings (Jon Skeet's blog) 记忆与弦乐(Jon Skeet的博客)

Benchmarking C# Struct and Object Sizes 标定C#结构和对象大小

Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects 深入到.NET Framework内部,以查看CLR如何创建运行时对象

How Much Memory Does a C# String Take Up C#字符串占用多少内存

It is due to the padding for types to fit on address boundaries. 这是由于类型的填充要适合地址边界。

This will depends on the types you are using, the runtime and the StructLayoutAttribute used for the type. 这将取决于您使用的类型,运行时和用于该类型的StructLayoutAttribute

if you look at Int32 with reflector you will see: 如果您看带有反射器的Int32 ,您将看到:

StructLayout(LayoutKind.Sequential)

This means that it can be noncontiguous : 意味着可以是不连续的

The members of the object are laid out sequentially, in the order in which they appear when exported to unmanaged memory. 对象的成员按顺序排列,并按照导出到非托管内存时出现的顺序排列。 The members are laid out according to the packing specified in StructLayoutAttribute.Pack, and can be noncontiguous. 成员根据StructLayoutAttribute.Pack中指定的包装进行布局,并且可以是不连续的。

The StructLayoutAttribute.Pack value is unset this means that it is 0 (defaultvalue) 未设置StructLayoutAttribute.Pack值,这意味着它是0(默认值)

A value of 0 indicates that the packing alignment is set to the default for the current platform. 值为0表示当前平台的装箱对齐设置为默认值。 It is usually 4byte for x86 and 8byte for x64 but it is optimized by the CLR in base of the sistem and those value may vary 对于x86, 通常为 4字节;对于x64, 通常为8字节,但是它由系统基础上的CLR优化,并且这些值可能会有所不同

You can see it with: 您可以通过以下方式看到它:

#pragma pack(show)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM