小编Ami*_*ari的帖子

.NET Core 中类内部的结构对齐

我试图理解为什么只包含 int 的结构在类中占用 8 个字节的内存。

考虑以下代码;

static void Main()
{
    var rand = new Random();

    var twoIntStruct = new TwoStruct(new IntStruct(rand.Next()), new IntStruct(rand.Next()));
    var twoInt = new TwoInt(rand.Next(), rand.Next());

    Console.ReadLine();
}

public readonly struct IntStruct
{
    public int Value { get; }

    internal IntStruct(int value)
    {
        Value = value;
    }
}

public class TwoStruct
{
    private readonly IntStruct A;
    private readonly IntStruct B;

    public TwoStruct(
        IntStruct a,
        IntStruct b)
    {
        A = a;
        B = b;
    }
}

public class …
Run Code Online (Sandbox Code Playgroud)

c# memory struct memory-alignment .net-core

10
推荐指数
1
解决办法
776
查看次数

标签 统计

.net-core ×1

c# ×1

memory ×1

memory-alignment ×1

struct ×1