Class 引用结构 - 分配

Class referencing a struct - allocation

class Foo
{
    public Bar StructProperty { get; set; }
    public int IntProperty { get; set; }
}

struct Bar
{
}

假设我有一个 class 结构 属性。我做了一个var foo = new Foo()foo.StructProperty 在内存中是如何布局的?是吗:

  1. 盒装上堆或
  2. 包含在属于 foo 对象本身的堆地址 space 中(就像 foo.IntProperty 被布局一样)?
  1. Contained within the heap address space belonging to the foo object itself (just like foo.IntProperty is laid out)?

这是正确的。

口头禅 "structs are allocated on the stack, classes are allocated on the heap" 在这里具有误导性——作为其他对象(其他 类 或结构)的一部分的结构存储在用于这些对象的内存中。 int 在这方面与任何其他结构类型没有什么不同。