递归是如何工作的

Sta*_*y V 2 c# recursion

这是我的代码

using System;
public class Program
{
   public static void Method(int flowerInVase)
      {
         if (flowerInVase > 0)
         {
             Method(flowerInVase - 1);
             Console.WriteLine(flowerInVase);
         }
      }

   public static void Main()
   {
      Method(3);
   }
}
Run Code Online (Sandbox Code Playgroud)

我感兴趣的Console.WriteLine(flowerInVase);是方法调用自己,直到它被条件终止.只有在堆栈已满之后,它才会弹出上面的每个方法,并且控制台从最少1,2,3开始写入数字.

为什么console.writeline只有当堆栈弹出时才能工作,为什么它不会在方法转到终止的方式上写入数字,比如3,2,1?编译器只在完成递归时才使用writeline.

Yuc*_*uck 9

调用的结构如下所示.也许这个可视化将帮助您理解为什么数字打印1,2,3而不是3,2,1:

Method(3);
  flowerInVase > 0 ?
  Yes - Method(2);
    flowerInVase > 0 ?
    Yes - Method(1);
      flowerInVase > 0 ?
      Yes - Method(0);
        flowerInVase > 0 ?
        No
      WriteLine(1);
    WriteLine(2);
  WriteLine(3);
Run Code Online (Sandbox Code Playgroud)

原因是因为你的电话Method(flowerInVase - 1)来电之前来的WriteLine(flowerInVase).在有机会打印它所在的数字之前,执行会跳转到该方法的不同副本.