我编写了一个小型控制台应用程序来测试 sizeof运算符(operator):
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字节打包。
谁能解释一下?
最佳答案
那是因为编译器对齐成员,因此优化了它们的访问速度,而不是它们的内存占用。
可以添加
[StructLayout(LayoutKind.Sequential, Pack=1)]
在结构定义之前,它应该在 1 个字节的空间内对齐。
关于c# - sizeof 根据字段顺序给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16927382/