C#中递归的工作原理 [英] How recursion works in C#

查看:43
本文介绍了C#中递归的工作原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码

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);
   }
}

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

I am interested in line Console.WriteLine(flowerInVase); the method calls itself until it's terminated by the condition. And only after that when the stack is full it pops up each of the method from above and console writes the number starting from the least 1,2,3.

为什么 console.writeline 只在堆栈弹出时才起作用,为什么它不在方法去终止的路上写数字,比如 3,2,1?编译器仅在完成递归后才使用 writeline.

Why the console.writeline works only when stack pops up, why it ain't writing the numbers on the way methods go to the termination, like 3,2,1? The compiler uses writeline only when it's done doing recursion.

推荐答案

由于 if 语句中的行的排序方式,您得到了 1,2,3.

You're getting 1,2,3 because of the way the lines in your if statement are ordered.

Main() 调用 Method(3).
Method(3) 在有机会打印3"之前调用 Method(2).执行立即跳转到Method的顶部;您对 Method 的第一次调用,使用 flowersinvase=3,在递归调用完成之前不会完成.同样,Method(2) 立即调用 Method(1)Method(1) 调用 Method(0)>.

Main() calls Method(3).
Method(3) calls Method(2) before it has a chance to print "3". Execution immediately jumps to the top of Method; your first call to Method, with flowersinvase=3, won't complete until the recursive call does. Likewise, Method(2) immediately calls Method(1), and Method(1) calls Method(0).

Method(0) 什么都不做并返回到 Method(1),就在它停止的地方;下一行是您的 WriteLine 调用,它打印1"然后返回,它在它停止的地方接听对 Method(2) 的调用,打印2", 以此类推3".

Method(0) does nothing and returns to Method(1), exactly where it left off; the next line is your WriteLine call, which prints "1" and then returns, which picks up the call to Method(2) where it left off, printing "2", and so on for "3".

如果您调用的方法在跳转到它们递归调用的任何方法之前运行完成,您只会得到3,2,1",这不是 C# 的工作方式.关于方法调用你必须记住的一点是,一旦你调用了一个方法,执行会立即跳转到你调用的方法的开始处;方法调用后的代码在方法返回之前不会执行.

You would only get "3,2,1" if the methods you called ran to completion before jumping to any methods they called recursively, which is not how C# works. The thing you have to remember about method calls is that once you call a method, execution jumps immediately to the start of the method you called; the code after the method call will not execute until the method returns.

这篇关于C#中递归的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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