背景

多数情况下我们不需要关心栈的变化,不过个别场景下还是需要对此有所了解,如:指针操作,下文会给出一个具体的示例。另外,理解栈的变化对于理解作用域也有一定的好处,因为C#的局部变量作用域是基于栈的。

栈的变化规则

  • 方法调用会导致栈的生长,具体包括两个步骤:一、插入方法返回地址(下图中的Fn:);二、将实际参数按值(可以使用ref或out修饰)拷贝并插入到栈中(可以使用虚参数访问)。
  • 遇到局部变量定义会向栈中插入局部变量。
  • 遇到return语句会导致栈消亡,一直消亡到方法返回地址,并把return的返回值设置到方法返回地址中。
  • 这里先不考虑中括号导致的栈的消亡。

简单的示例

.NET:栈的生长与消亡

最后的小测试,输出的啥内容?

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace StackAndHeapStudy
 8 {
 9     unsafe class Program
10     {
11         static void Main(string[] args)
12         {
13             var test = new TestClass();
14             SetX(test);
15             Console.WriteLine(*test.X);
16             Console.WriteLine(*test.X);
17         }
18 
19         private static void SetX(TestClass test)
20         {
21             var X = 10;
22 
23             test.X = &X;
24         }
25     }
26 
27     unsafe class TestClass
28     {
29         public int* X;
30     }
31 }

备注

上大学期间学习过C++和C,此文只是靠回忆而写的,不一定正确,也希望兄弟们多批评。

 

相关文章:

  • 2021-09-13
  • 2021-12-05
  • 2021-07-01
  • 2021-12-28
  • 2021-10-12
  • 2021-06-12
  • 2019-01-09
猜你喜欢
  • 2021-10-11
  • 2021-11-17
  • 2022-01-08
  • 2021-09-19
  • 2021-08-09
  • 2019-05-19
  • 2020-06-09
  • 2021-12-10
相关资源
相似解决方案