对象中的值类型也存储在堆中吗?

发布于 2024-10-12 19:05:37 字数 115 浏览 4 评论 0原文

我可以想象这个问题已经被问了数千次,但我没有太多运气找到答案,而且这更多是出于好奇而不是需要。

深入研究 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

战皆罪 2024-10-19 19:05:37

安德鲁·黑尔是对的。有关完整详细信息,请参阅 Eric Lippert 的博客文章

我对“值类型存储在堆栈上”的神话感到不安......通常是错误的表述:该语句应该是“值类型可以存储在堆栈上”,而不是更常见的“值”类型始终存储在堆栈中”。

Andrew Hare is right. For the full details, see Eric Lippert's blog entry:

I'm disturbed by the myth that "value types go on the stack" ... It is usually stated incorrectly: the statement should be "value types can be stored on the stack", instead of the more common "value types are always stored on the stack".

哆啦不做梦 2024-10-19 19:05:37

它们存储在堆中,位于为引用类型分配的内存内部。此外,值类型通常存储在“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.

滥情哥ㄟ 2024-10-19 19:05:37

它们与对象本身一起存储在堆上。考虑这个问题的一个好方法是,当一个对象(具有值类型作为其状态的一部分)在堆上分配时,它的值类型也必须存在在那里,否则一旦堆栈展开,这些值类型就会消失用于创建该对象的代码。

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.

苍白女子 2024-10-19 19:05:37

是的,它们存储为堆的一部分。然而,正如 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文