我们来用一段测试代码验证一下这个 Server 结构体的内存使用情况:
var ip = new IpAddress(new Random().Next()); Console.WriteLine($"Size: {Marshal.SizeOf(ip)} bytes. Value: {ip.Address} = {ip}"); var s1 = new Server(ip, 8080, Protocol.https); var s2 = new Server(s1.Payload); s2.Address.Byte1 = 100; s2.Protocol = Protocol.ftp; Console.WriteLine($"Size: {Marshal.SizeOf(s1)} bytes. Value: {s1.Address} = {s1}"); Console.WriteLine($"Size: {Marshal.SizeOf(s2)} bytes. Value: {s2.Address} = {s2}");输出结果:
Size: 4 bytes. Value: 2102736192 = 64.53.85.125 Size: 8 bytes. Value: 64.53.85.125 = https://64.53.85.125:8080 Size: 8 bytes. Value: 100.53.85.125 = ftp://100.53.85.125:8080示例中,IP 地址偏移 0 字节,长度为 4 字节;端口号偏移 4 字节,长度为 2 字节;协议偏移 6 字节,长度为 1 字节。总长度应为 4+2+1=7 字节,但实际打印出来却是 8 字节,请问是为什么?
参考:https://bit.ly/3qmH92V