我有两个带有字节和布尔数组的结构:
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
似乎a boolean
需要4个字节的存储空间。理想情况下,a boolean
只需占用一位(false
或true
,0
或1
,等等)。
这是怎么回事 是boolean
类型真的如此低效?