为什么存储在堆栈上结构,而类得到存储在堆(.NET)?堆栈、结构、NET

2023-09-02 10:26:25 作者:明知是毒却一饮而尽

我知道,类和结构之间的区别之一是,结构的实例获取存储在存储堆栈和类实例(对象)。

I know that one of the differences between classes and structs is that struct instances get stored on stack and class instances(objects) are stored on the heap.

由于类和结构都非常相似。是否有人知道这个特殊的区别有什么区别?

Since classes and structs are very similar. Does anybody know the difference for this particular distinction?

推荐答案

(编辑以弥补评论点)

要强调的是:有值类型和引用类型之间的差异和相似之处,但这些差异都什么做栈VS堆,以及一切与复制语义VS参考 - 语义。特别是,如果我们这样做:

To emphasise: there are differences and similarities between value-types and reference-types, but those differences have nothing to do with stack vs heap, and everything to do with copy-semantics vs reference-semantics. In particular, if we do:

Foo first = new Foo { Bar = 123 };
Foo second = foo;

然后是第一,第二谈的同一个副本?或不同的副本?碰巧的堆栈是的处理的值类型变量作为一个方便快捷的途径。但是,这是一个实现细节。

Then are "first" and "second" talking about the same copy of Foo? or different copies? It just so happens that the stack is a convenient and efficient way of handling value-types as variables. But that is an implementation detail.

(编辑完)

再整个值类型进入堆叠的东西...... - 值类型的不要总是在栈上;

Re the whole "value types go on the stack" thing... - value types don't always go on the stack;

如果他们是在一类领域 如果他们是盒装 如果他们是捕获变量 如果他们是在迭代器块

然后他们去堆(最后两个实际上是第一只异国情调的例子)

then they go on the heap (the last two are actually just exotic examples of the first)

class Foo {
    int i; // on the heap
}

static void Foo() {
    int i = 0; // on the heap due to capture
    // ...
    Action act = delegate {Console.WriteLine(i);};
}

static IEnumerable<int> Foo() {
    int i = 0; // on the heap to do iterator block
    //
    yield return i;
}

此外,埃里克利珀(如前所述)具有excellent关于这个问题的博客条目

Additionally, Eric Lippert (as already noted) has an excellent blog entry on this subject