内存中的C#类实例大小

时间:2018-08-08 08:14:24

标签: c# memory memory-management

我有以下情况:

public class Test
{
    public void main()
    {
        //arrange
        var a = new A(4,2);
        var b = new B(3, 6, 6, 4);

        //act
        var a1 = a.ObjectToByteArray();
        var b1 = b.ObjectToByteArray();

    }

    [StructLayout(LayoutKind.Sequential, Pack = 1, Size = 3)]
    public class A
    {
        [MarshalAs(UnmanagedType.U1, SizeConst = 1)]
        byte a1;
        [MarshalAs(UnmanagedType.U1, SizeConst = 1)]
        byte a2;
        [MarshalAs(UnmanagedType.U1, SizeConst = 1)]
        byte a3;

        public A(byte a1, byte a2)
        {
            this.a1 = a1;
            this.a2 = a2;
            this.a3 = 9;
        }
    }

    [StructLayout(LayoutKind.Sequential, Pack = 1, Size = 6)]
    public class B : A
    {
        [MarshalAs(UnmanagedType.U1, SizeConst = 1)]
        byte b1;

        [MarshalAs(UnmanagedType.U1, SizeConst = 1)]
        byte b2;

        [MarshalAs(UnmanagedType.U1, SizeConst = 1)]
        byte b3;

        public B(byte a1, byte a2, byte b1, byte b2) : base(a1, a2)
        {
            this.b1 = b1;
            this.b2 = b2;
            this.b3 = 8;
        }
    }
}

然后是扩展方法:

public static byte[] ObjectToByteArray<T>(this T source)
    {
        int rawSize = Marshal.SizeOf(typeof(T));
        var rawData = new byte[rawSize];

        //var h1 = GCHandle.Alloc(source, GCHandleType.Pinned);
        //var ptr = h1.AddrOfPinnedObject();
        //h1.Free();

        var handle = GCHandle.Alloc(rawData, GCHandleType.Pinned);
        Marshal.StructureToPtr(source, handle.AddrOfPinnedObject(), false);

        handle.Free();

        return rawData;

    }

A类型(a)大小的第一个实例由Marshal.SizeOf(typeof(T))函数确定是正确的(3个字节),但是当B类型(b)的第二个实例出现时,相同的函数返回7个字节,而不是6个字节。 谁能解释我在做什么错,或者这是预期的行为?

预先感谢, 朱利安

0 个答案:

没有答案