c# 关于字段内存排序
关键字:StructLayout、LayoutKind.Explicit、FieldOffset
[StructLayout(LayoutKind.Explicit)] public class AA { [FieldOffset(0)] public readonly Int16 m_x = 55; [FieldOffset(0)] public readonly Byte m_b = (Byte)22; }
AA m = new AA(); var d1 = m.m_b; var d2 = m.m_x;
输出的值:
字段定义交换顺序:
[StructLayout(LayoutKind.Explicit)] public class AA { [FieldOffset(0)] public readonly Byte m_b = (Byte)22; [FieldOffset(0)] public readonly Int16 m_x = 55; }
同样的偏移量,输出的值以最后一个字段的值为准。
CLR保持开发人员的定义字段的顺序。