对象中的值类型也存储在堆中吗?
我可以想象这个问题已经被问了数千次,但我没有太多运气找到答案,而且这更多是出于好奇而不是需要。
深入研究 C# 的具体细节,我想知道既然对象存储在堆中,那么对象中的值类型也存储在堆中还是放置在堆栈中?
I can imagine this question has been asked thousands of times, but I didn't have much luck in finding the answer, plus this is more out of curiosity than need.
Digging into the nuts and bolts of C#, I was wondering since objects are stored in the heap, are the value types within the objects stored in the heap as well or are they placed in the stack?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
安德鲁·黑尔是对的。有关完整详细信息,请参阅 Eric Lippert 的博客文章:
Andrew Hare is right. For the full details, see Eric Lippert's blog entry:
它们存储在堆中,位于为引用类型分配的内存内部。此外,值类型通常存储在“the堆栈”。但是,CLI 规范并未指定存储值类型的内存池所在的位置 - 这是一个无关紧要的实现细节。
They are stored in the heap, inside of the memory allocated for the reference type. In addition, value types are often stored in places other than "the stack". However, the CLI spec does not specify where the memory pool that stores value types resides - it's an implementation detail that should not matter.
它们与对象本身一起存储在堆上。考虑这个问题的一个好方法是,当一个对象(具有值类型作为其状态的一部分)在堆上分配时,它的值类型也必须存在在那里,否则一旦堆栈展开,这些值类型就会消失用于创建该对象的代码。
Those are stored on the heap, with the objects themselves. A good way to think about this is that when an object (that has value types as part of its state) is allocated on the heap, it's value types must live there as well, otherwise those value types would disappear as soon as the stack unwound for the code that created the object.
是的,它们存储为堆的一部分。然而,正如 Eric Lippert 在多个场合所描述的那样,这都是一个实现细节。我建议您阅读他的博客文章,此是最新的,并且这些 两个也很重要。
Yes, they're stored as part of the heap. However, it's all an implementation detail, as Eric Lippert has described on multiple occasions. I suggest you read his blog posts about it, this being the most recent one, and these two also being important.