为什么包含自定义结构实际上会增加我的c#类的大小?

为什么包含自定义结构实际上会增加我的c#类的大小?,c#,memory,struct,C#,Memory,Struct,我有一个有几个浮动的类,还有一些其他字段 public class tResult { public byte Days; public int UpCount; public int DownCount; public int SameCount; public float UpRatio; public float DownRatio; public float SameRatio; public float UpAv

我有一个有几个浮动的类,还有一些其他字段

 public class tResult
    {
    public byte Days;
    public int UpCount;
    public int DownCount;
    public int SameCount;
    public float UpRatio;
    public float DownRatio;
    public float SameRatio;
    public float UpAverage;
    public float DownAverage;
    public float Average;
    public float OccurancesCF;
    public float DirectionCF;
    }
使用
Float
而不是
Percentage
,我的类每个占用88字节(使用Jon Skeet的测试在
GC.GetTotalMemory(true)
调用之间创建1M个实例)

当我用
百分比
类(2字节数据)替换5个
浮动(4字节)时,我的大小增加到96字节

public struct Percentage : IComparable
{
    public Int16 Hundredths;
    public Percentage(double X) { Hundredths = (Int16)(X * 100); }
    public double Ratio { get { return Hundredths / 100.0; } set { Hundredths = (Int16)(value * 100); } }
    public override string ToString() => (Hundredths / 100.0).ToString("##0.00");
    public int CompareTo(object obj) => Hundredths.CompareTo(((Percentage)obj).Hundredths);
}


我的问题是为什么它上升而不是下降?我在这里读到的所有内容(包括Jon和Eric Lippert的帖子)都让我觉得它们应该按大小重新排列,因此应该减少约10个字节。

我假设类中
百分比
成员的对齐导致了这种行为。编译器可能不会在2字节边界上对齐它们。尝试将另外两个字节添加到Percentage,看看它是否没有区别。请添加带有“Percentage”的结果类。Jonathan,我添加了另一个2字节变量,它没有区别。您的测量结果似乎不准确,在32位模式下,它从56字节变为56字节,在64位模式下,它从64字节变为88字节。浮点始终与4对齐,结构在32位模式下与4对齐,在64位模式下与8对齐。@hans-这在64位模式下处于调试模式。内部值类型(int16、byte等)似乎与8字节不对齐,有没有办法在我们自己的构造中复制它?我可以使用带有扩展方法的int16生成一个2字节的FP数(非常适合百分比),但显然我想用一个struct。
    public class tResult
    {
            public byte Days;
            public int UpCount;
            public int DownCount;
            public int SameCount;
            public Percentage UpRatio;
            public Percentage DownRatio;
            public Percentage SameRatio;
            public float UpAverage;
            public float DownAverage;
            public float Average;
            public Percentage OccurancesCF;
            public Percentage DirectionCF;
    }