【发布时间】:2013-06-05 19:27:45
【问题描述】:
我编写了一个小型控制台应用程序来测试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 个字节。
谁能解释一下?
【问题讨论】:
-
你可能想看看here