结构体成员定义的顺序也会影响结构体的大小,内存对齐,内存填充
using System;
using System.Runtime.InteropServices;
struct StrcutOne
{
public int b; // 4 bytes
public byte a; // 1
public byte c; // 1
// 4+1+1+2(在填充两个2个字节) = 8 字节
}
struct StrcutTwo
{
public byte a; // 1 byte
public int b; // 4 bytes
public byte c; // 1 byte
// 1+3(填充)+4+1+3(填充) = 12
}
class Program
{
static void Main()
{
Console.WriteLine($"Size of ChangedOrder: {Marshal.SizeOf<StrcutOne>()} bytes");
Console.WriteLine($"Size of ExampleStruct: {Marshal.SizeOf<StrcutTwo>()} bytes");
}
}