我编写了一个小型控制台应用程序来测试sizeof运算符:
public class Program
{
public static unsafe void Main(string[] args)
{
// Native
Console.WriteLine("The size of bool is {0}.", sizeof(bool));
Console.WriteLine("The size of short is {0}.", sizeof(short));
Console.WriteLine("The size of int is {0}.", sizeof(int));
Console.WriteLine("The size of long is {0}.", sizeof(long));
// Custom
Console.WriteLine("The size of Bool1 is {0}.", sizeof(Bool1));
Console.WriteLine("The size of Bool2 is {0}.", sizeof(Bool2));
Console.WriteLine("The size of Bool1Int1Bool1 is {0}.", sizeof(Bool1Int1Bool1));
Console.WriteLine("The size of Bool2Int1 is {0}.", sizeof(Bool2Int1));
Console.WriteLine("The size of Bool1Long1 is {0}.", sizeof(Bool1Long1));
Console.WriteLine("The size of Bool1DateTime1 is {0}.", sizeof(Bool1DateTime1));
Console.Read();
}
}
public struct Bool1
{
private bool b1;
}
public struct Bool2
{
private bool b1;
private bool b2;
}
public struct Bool1Int1Bool1
{
private bool b1;
private int i1;
private bool b2;
}
public struct Bool2Int1
{
private bool b1;
private bool b2;
private int i1;
}
public struct Bool1Long1
{
private bool b1;
private long l1;
}
public struct Bool1DateTime1
{
private bool b1;
private DateTime dt1;
}
给出以下输出:
声明字段的顺序似乎对结构的大小起作用。
我期待Bool1Int1Bool1
返回的大小为6 (1 + 4 + 1) 但它却给出了12 (我想是 4 + 4 + 4??) !因此,编译器似乎通过将每个4 个字节打包来对齐成员。
如果我在 32 位或 64 位系统上,它会改变什么吗?
第二个问题,对于有long
类型的测试,这次bool
是用8个字节打包。谁能解释一下?