怪奇物语

怪奇物语

首页 新随笔 联系 管理

字节填充,内存对齐,为什么结果是4个字节,而不是三个字节


using System;
using System.Runtime.InteropServices;

public struct ExampleStruct
{
    public byte b;
    public short s;
    // 你以为的是:1+2 = 3
    // 实际是: 1+1(填充)+2 = 4
}

class Program
{
    static void Main()
    {
        Type t = typeof(ExampleStruct);
        Console.WriteLine($"Size of ExampleStruct: {Marshal.SizeOf<ExampleStruct>()} bytes");
    }
}

posted on 2024-09-07 16:11  超级无敌美少男战士  阅读(15)  评论(0)    收藏  举报