我正在尝试理解为什么一个只包含 int 的结构体在类内占用 8 字节的内存。
考虑以下代码;
static void Main()
{
var rand = new Random();
var twoIntStruct = new TwoStruct(new IntStruct(rand.Next()), new IntStruct(rand.Next()));
var twoInt = new TwoInt(rand.Next(), rand.Next());
Console.ReadLine();
}
public readonly struct IntStruct
{
public int Value { get; }
internal IntStruct(int value)
{
Value = value;
}
}
public class TwoStruct
{
private readonly IntStruct A;
private readonly IntStruct B;
public TwoStruct(
IntStruct a,
IntStruct b)
{
A = a;
B = b;
}
}
public class TwoInt
{
private readonly int A;
private readonly int B;
public TwoInt(
int a,
int b)
{
A = a;
B = b;
}
}
现在,当我使用dotMemory对这两个实例进行分析时,我得到了以下结果:
虽然int和intStruct在堆栈上都占用4字节的内存,但看起来它们在堆上的类大小是不同的,并且结构体始终对齐到8字节。
是什么导致了这种行为?
TwoStruct
上使用[StructLayoutAttribute(LayoutKind.Sequential, Pack = 4)]
似乎可以解决这个问题。 - Guru StronStructLayoutAttribute
可以被添加到类中,直到今天! - Sweeper