.net框架中值类型和引用类型的内存分配 [英] memory allocation of value types and reference types in .net framework

查看:26
本文介绍了.net框架中值类型和引用类型的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一篇我可以阅读的高级文章可以解释如何在 .net 框架中为不同类型(值和引用)分配内存.

例如,我们知道值类型在堆栈上分配了空间,但如何管理?

还有如何在堆中管理引用类型以及实际值存储在哪里.(引用类型和任何类一样,都会包含很多值类型,保存在哪里,如何管理)

解决方案

它比您想象的要复杂.甚至您声称在堆栈上分配了值类型"也是不正确的.例如:

class Foo{整数 x;}

int 是一种值类型,但 x 的值将始终在堆上,因为它将与作为类的 Foo 实例的其余数据一起存储.

此外,为匿名函数和迭代器块捕获的变量让生活变得更加棘手.

我有一篇关于 C# 堆/堆栈内存的文章,您可能会觉得有用,但您可能还想阅读 Eric Lippert 在 "堆栈是一个实现细节".特别是,未来的 C# 编译器可以决定将其所有局部变量存储在堆上,使用堆栈只是为了保存对在方法开始时创建的实例的引用......这不会违反 C# 规范全部.

Is there an advanced article which I can read that can explain how memory is allocated for different types (value and reference) in .net framework.

for example we know that value types are allocated space on a stack, but how is that managed?

Also how are reference types managed in a heap and where are the actual values stored. (Reference type like any Class will contain many value types, where are they saved and how are they managed)

解决方案

It's more complicated than you might think. Even your claim that "value types are allocated on the stack" isn't correct. For example:

class Foo
{
    int x;
}

int is a value type, but the value for x will always be on the heap because it will be stored with the rest of the data for the instance of Foo which is a class.

Additionally, captured variables for anonymous functions and iterator blocks make life trickier.

I have an article about C# heap/stack memory you may find useful, but you might also want to read Eric Lippert's blog post on "The stack is an implementation detail". In particular, a future C# compiler could decide to store all of its local variables on the heap, using the stack just to hold a reference to an instance created at the start of the method... that wouldn't defy the C# spec at all.

这篇关于.net框架中值类型和引用类型的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆