C#结构体大小问题
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Struct { class Program { static void Main(string[] args) { Console.WriteLine("结构体大小:"+Marshal.SizeOf(new DataSize())); Console.ReadKey(); } } //可序列化 设置对齐值为1 //[Serializable, StructLayout(LayoutKind.Sequential, Pack = 1)] public struct DataSize { public ushort a;//对齐值2 public char b;//1 public ushort c;//2 public uint d;//4 public char e;//1 public char f;//1 public char g;//1 public int h;//4 }; }
按照最大的对齐值对齐,上面最大的对齐值为4,2+1=3<4 3+2=5>4,所以a和b占4个,c占4个,d占4个,e,f,g占4个,h占4个共20个字节。若设置对齐值为1,那么直接将所有对齐值相加即可为16.
输出结果
结构体大小:20
转载 https://blog.csdn.net/jueduiwudi6/article/details/80721108
4556