我有两个带有字节和布尔值数组的结构:
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct struct1
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public byte[] values;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct struct2
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public bool[] values;
}
以下代码:
class main
{
public static void Main()
{
Console.WriteLine("sizeof array of bytes: "+Marshal.SizeOf(typeof(struct1)));
Console.WriteLine("sizeof array of bools: " + Marshal.SizeOf(typeof(struct2)));
Console.ReadKey();
}
}
结果如下:
sizeof array of bytes: 3
sizeof array of bools: 12
boolean
似乎占用4个字节的存储空间。理想情况下,boolean
只需要一位(false
或 true
、 0
或 1
等等).
这里发生了什么? boolean
类型真的这么低效吗?