当使用结构/类时,大小总是与特定大小对齐,在每个架构上它可能不同,但通常是 4,所以如果你在 bool 之后有 int,我们从 4 的乘法开始,导致处理器读取 4 个字节块。
这是在设置类(或结构)中成员的顺序时值得考虑的事情
示例:
[StructLayout(LayoutKind.Sequential)]
public struct Sample1
{
public bool a1;//take 1 byte but align to 4
}
public struct Sample2
{
public bool a1;//take 1 byte but align to 4
public int a2;//take 4 bytes (32bit machine) start at a multiplication of 4
public bool a3;//take 1 byte but align to 4
}
public struct Sample3
{
//here the compiler (with the right optimizations) can put all the bools one after the other without breaking the alignment
public bool a1;
public bool a2;
public bool a3;
public bool a4;
public int a5;
}
int size1 = Marshal.SizeOf(typeof (Sample1)); // 4
int size1 = Marshal.SizeOf(typeof (Sample2)); // 12
int size1 = Marshal.SizeOf(typeof (Sample3)); // 8
int size2 = sizeof (bool); // 1