c# - 如何计算结构实例的大小?

标签 c# struct

这个问题纯粹是为了满足我的兴趣。读书Choosing Between Classes and Structures该页面显示“它的实例大小小于 16 字节。”。

给定这个简单的不可变结构

public struct Coordinate
{
    private readonly double _latitude;
    private readonly double _longitude;

    public Coordinate(double latitude, double longitude)
    {
        _latitude = latitude;
        _longitude = longitude;
    }

    public double Latitude
    {
        get { return _latitude; }
    }

    public double Longitude
    {
        get { return _longitude; }
    }
}

属性是否也计入 16 字节的限制?还是只计算字段?

如果后者使用 struct 不符合 Microsoft 提供的指南,因为 double 是 8 个字节?两个 double 将是 16 个字节,正好是 16 个字节且不少于此。

最佳答案

只有字段才重要。

所以在这种情况下,您有两个 64 位(8 字节)字段;你刚好在你的启发式范围内。

请注意,如果您使用任何 auto-implemented properties然后编译器将创建“隐藏”字段来支持这些属性,因此您的总和也应该考虑到这些。

例如,这个结构也需要 16 个字节:

public struct Coordinate
{
    public Coordinate(double latitude, double longitude) : this()
    {
        Latitude = latitude;
        Longitude = longitude;
    }

    public double Latitude { get; private set; }
    public double Longitude { get; private set; }
}

关于c# - 如何计算结构实例的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6521147/

相关文章:

c# - 在与 Ninject 绑定(bind)时使用通用类型——这可能吗?

pointers - Golang 通过引用结构成员值传递变量

Mathematica 中的结构数据类型?

c - 如何将结构初始化为空?

c# - 确保 NLOG 确实进行日志记录?

c# - Silverlight/.net 的条码阅读器组件、资源、推荐、动物之森?天啊

C - 在没有头文件的情况下在多个文件中构造

c - 由于结构,for 循环中的段错误?

c# - 将 RichTextBox.Text 数据绑定(bind)到字符串

c# - 当 DatagridviewComboBox 选定索引更改时更改 DatagridviewTextBox 文本