gpt4 book ai didi

c# - .net中引用类型内值类型的内存分配

转载 作者:太空狗 更新时间:2023-10-29 21:45:57 24 4
gpt4 key购买 nike

我认为这是一个非常微不足道的问题,但我无法在网上得到明确的答案。

我有一个包含值类型和引用类型的类。考虑到类中的引用类型将在执行期间的某个时间实例化,如何为此类的每个成员分配内存?如何为每个成员存储和访问指针?在哪种内存结构中创建哪种类型,即堆栈或堆?

我知道,如果在我的代码中只使用一个值类型的变量,那么它的值和所有其他细节(如它的类型等)都存储在堆栈中。类似地,如果引用类型被实例化,则在堆中创建实际对象,并将指向该内存位置的指针存储在堆栈中。但是类中存在的值类型(引用类型)呢?它们存储在哪里以及如何访问?

我在下面给出了此类的示例。引用此类的答案将非常有帮助。

public class Employee
{
public int EmpNo { get; set; }
public string EmpName { get; set; }
public BankAccDetails AccDetails { get; set; }
}

public class BankAccDetails
{
//Other properties here
}

最佳答案

But what about value types present inside a class (reference type)? Where are they stored and how are they accessed?

值类型存储在它们被声明的地方。在您的情况下,它们将在堆上。

但是您应该看到以下有关 C# 中的内存管理的文章。

The Truth about value types - Eric Lippert

in the Microsoft implementation of C# on the desktop CLR, value types are stored on the stack when the value is a local variable or temporary that is not a closed-over local variable of a lambda or anonymous method, and the method body is not an iterator block, and the jitter chooses to not enregister the value.

The Stack Is An Implementation Detail, Part One - Eric Lippert
Memory in .NET - what goes where - Jon Skeet

关于c# - .net中引用类型内值类型的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11876503/

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