gpt4 book ai didi

c# - 如何在堆上存储 int 或其他 "C# value types"(使用 C#)?

转载 作者:太空狗 更新时间:2023-10-30 00:20:40 28 4
gpt4 key购买 nike

我正在通过 Troelsen 的 Pro C# 书籍自学 C#。

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

  • 当与 int 等值类型一起使用时,使用 new 似乎只是调用 int 默认构造函数,但此类 int 的值仍将存储在堆栈中

我知道所有对象/结构等都存储在堆上,无论是否使用 new

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

最佳答案

您可以将任何值类型装箱为 System.Object 类型,以便将其存储在托管堆上:

int number = 1;
object locatedOnTheHeap = number;

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

这是必知 MSDN 论文中的一个经典示例: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

顺便说一句,IIRC 有时 JIT 会优化代码,因此 int 类型的值类型对象存储在 CPU 寄存器中而不是堆栈中。

关于c# - 如何在堆上存储 int 或其他 "C# value types"(使用 C#)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9894169/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com