堆、栈、内存管理

在某位(实在忘记是谁了,好像博主把连接里的文章翻译成中文了)的博客里看到一个连接,题目是C#Heap(ing)Vs Stack(ing) in.NET,主要就是讲内存管理,非常具体生动,里面还有很多图例。http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx。我现在只看了Part I和Part II。继续复述总结加强理解。

Stack: is more or less responsible for keeping track of what's executing in our code (or what's been "called"). It's self-maintaining, meaning that it basically takes care of its own memory management. When the top "box" is no longer used, it's thrown out.

Heap: is more or less responsible for keeping track of our objects. Heap has to worry about Garbage Collection.

程序执行时,主要有四种类型要存放在Stack 和Heap中,他们是:值类型,引用类型,指针(Pointers,我觉得这个是指向引用类型的值类型或者引用类型),Instructions(还没遇到过,不知道怎么翻译)

C#中的值类型:

  • bool
  • byte
  • char
  • decimal
  • double
  • enum
  • float
  • int
  • long
  • sbyte
  • short
  • struct
  • uint
  • ulong
  • ushort

引用类型:

  • class
  • interface
  • delegate
  • object
  • string

怎么决定什么类型放在什么位置?文章讲了一个黄金准则:

1. 引用类型永远存储在Heap里

2. 值类型在哪里声明就存储在哪里

文章里举了很多从简单到复杂的例子来解释这两条准则,后面的的确很难。先记住这个准则。

原文地址:https://www.cnblogs.com/amigo/p/3335392.html