C# struct 中的内存对齐

2022-09-03  本文已影响0人  百里有声

c#中char占两个字节,ushort占2个字节,int占4个字节

struct下字段占用按8的倍数补齐

   struct AAAA
    {
        public char name;
        public ushort value;
        public ushort at;
        public char end;
    }
    struct BBBB
    {
        public char name;
        public char second;
        public ushort value;
        public ushort at;
        public char end;
        public int t;
        public int e;
    }
    struct EEEE
    {
        public char name;
        public char second;
        public ushort value;
        public ushort at;
        public char end;
    }
    struct CCCC
    {
        public ushort value;
        public ushort at;
        public char name;
        public char end;
    }
    struct DDDD
    {
        public char name;
        public char end;
    }
    class TestO
    {
        public int t = 1;
        public int e = 1;
        public int m = 1;
        public int p = 1;
    }
    class TestP
    {
        public AAAA a;
        public BBBB b;
        public CCCC c;
        public DDDD d;
    }
    class TestQ
    {
        public AAAA a;
        public EEEE e;
        public CCCC c;
    }

 class Program
    {
        static void Main(string[] args)
        {
            TestP p = new TestP();
            p.a.name = 'A';
            p.a.value = 'a';
            p.a.end = '1';

            p.b.name = 'B';
            p.b.value = 'b';
            p.b.end = '1';
            p.b.t = 1000;
            p.b.e = 1000;

            p.c.name = 'C';
            p.c.value = 'c';
            p.c.end = '1';

            p.d.name = 'D';
            p.d.end = '1';

            TestQ q = new TestQ();
            q.a.name = 'A';
            q.a.value = 'a';
            q.a.end = '1';

            q.e.name = 'e';
            q.e.value = 'e';
            q.e.end = '1';

            q.c.name = 'C';
            q.c.value = 'c';
            q.c.end = '1';

            TestO o = new TestO();

        }
 }
image.png
上一篇下一篇

猜你喜欢

热点阅读