c# - sizeof 根据字段顺序给出不同的结果

标签 c# .net structure sizeof

我编写了一个小型控制台应用程序来测试 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;
}

给出以下输出:

sizeof result

似乎声明字段的顺序对结构的大小有影响

我原以为 Bool1Int1Bool1 返回的大小是 6 (1 + 4 + 1),但它返回的是 12(我想是 4 + 4 + 4??)!因此,编译器似乎通过按 4 个字节打包 来对齐成员。

如果我在 32 位或 64 位系统上,它会改变什么吗?

第二个问题,对于long类型的测试,这次bool8字节打包。 谁能解释一下?

最佳答案

那是因为编译器对齐成员,因此优化了它们的访问速度,而不是它们的内存占用。

可以添加

[StructLayout(LayoutKind.Sequential, Pack=1)]

在结构定义之前,它应该在 1 个字节的空间内对齐。

关于c# - sizeof 根据字段顺序给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16927382/

相关文章:

c# - 运算符 '==' 不能应用于 linq to entity 中类型为 'System.Guid' 和 'string' 的操作数

c - 程序终止后变量保留值,如何防止? C

c - 将结构数组嵌套到另一个结构中

从主函数调用结构值时无法打印值

c# - 如何使用 LINQ 选择具有最高值的项目?

c# - SQLDependency with DI

c# - 停止突出显示所选项目 WPF ComboBox

c# - Linq连接查询错误

c# - 无法在 Chrome v76 中隐藏 "Chrome is being controlled by automated software"信息栏

c# - 网络核心 : Find Data Type for any Variable Field in Class