gpt4 book ai didi

c# - 为什么 WinDbg 对 c# 类和结构显示相同的大小?

转载 作者:太空宇宙 更新时间:2023-11-03 10:54:11 24 4
gpt4 key购买 nike

首先我问了一个关于类(class)规模的问题,我得到了答案,我也明白了。现在,当我看到 WinDbg 为相同类型的 class 和 struct 显示相同的大小时,我感到很困惑,因为我读过结构不包含 SyncBlock 那么结构的大小应该比类的大小少 8 个字节。

我的第一个问题:

结构没有 SyncBlock 字段是否正确?

下面是我的类(class):

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

结构是:

public struct MyStruct
{
public int Age { get; set; }
public double Amount { get; set; }
public string Name { get; set; }
}

通过 WinDbg,我得到了 MyClass 和 MyStruct 的 size = 40

对于类我理解它是因为它有:

SyncBlock  = 8 bytes 
TypeHandle = 8 bytes
String ref = 8 bytes
Int32 = 4 bytes
Double = 8 bytes
Total = 36 bytes

因为它需要选择 8 字节的边界,所以它变成了 40 字节,但为什么 struct 也是 40 字节?

我在 64 位系统上运行。以下是 WinDbg 的输出: enter image description here enter image description here

最佳答案

好吧,我运行了以下代码:

[TestMethod]
public void TestSize()
{
MyStruct s = new MyStruct();
Debug.Print(Marshal.SizeOf(s).ToString());
}

并得到了预期的结果24。

关于c# - 为什么 WinDbg 对 c# 类和结构显示相同的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20101584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com