如何在堆(使用C#)上存储int或其他“C#值类型”?(How do you store an int or other “C# value types” on the heap (with C#)?

编程入门 行业动态 更新时间:2024-10-14 14:19:53
如何在堆(使用C#)上存储int或其他“C#值类型”?(How do you store an int or other “C# value types” on the heap (with C#)?)

我通过Troelsen的Pro C#书从事自己的C#教育。

我熟悉堆栈和堆以及C#如何存储这些类型的东西。 在C ++中,每当我们使用new我们都会收到指向堆上的东西的指针。 但是,在C#中, new行为似乎与我不同:

当使用像int这样的值类型时,使用new似乎只是调用int默认构造函数,但是这样的int的值仍然会存储在堆栈中

我知道所有对象/结构体等都存储在堆中,而不管是否使用new的。

所以我的问题是:如何在堆上实例化一个int ? (这与'拳击'有什么关系?)

I'm engaged in educating myself about C# via Troelsen's Pro C# book.

I'm familiar with the stack and heap and how C# stores these sorts of things. In C++, whenever we use new we receive a pointer to something on the heap. However, in C# the behavior of new seems different to me:

when used with value types like an int, using new seems to merely call the int default constructor yet the value of such an int would still be stored on the stack

I understand that all objects/structs and such are stored on the heap, regardless of whether or not new is used.

So my question is: how can I instantiate an int on the heap? (And does this have something to do with 'boxing'?)

最满意答案

您可以将任何值类型添加到System.Object类型,以便将其存储在托管堆中:

int number = 1; object locatedOnTheHeap = number;

另一个问题是为什么你需要这个。

这是必须知道的MSDN论文的一个典型例子: 拳击和取消装箱(C#编程指南)

当CLR选择一个值类型时,它将值包装在System.Object中并将其存储在托管堆上。 拳击用于在垃圾收集堆中存储值类型。 Boxing是一个值类型到类型对象的隐式转换,或者是由这个值类型实现的任何接口类型。 装箱值类型会在堆上分配一个对象实例并将该值复制到新对象中。

我明白所有的对​​象/结构等都存储在堆中

顺便说一下,IIRC有时候JIT会优化代码,所以像int这样类型的值类型对象存储在CPU寄存器中而不是堆栈中。

You can box any value type to System.Object type so it will be stored on the managed heap:

int number = 1; object locatedOnTheHeap = number;

An other question is why you need this.

This is a classic example from the must-know MSDN paper: Boxing and Unboxing (C# Programming Guide)

When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

.

I understand that all objects/structs and such are stored on the heap

BTW, IIRC sometimes JIT optimizes code so value type objects like of type like int are stored in the CPU registers rather than stack.

更多推荐

本文发布于:2023-08-06 21:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1455067.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:或其他   类型   如何在   int   heap

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!