如何递归调用 C# 方法?
csharpprogrammingserver side programming更新于 2025/5/19 4:22:17
要递归调用 C# 方法,您可以尝试运行以下代码。这里,数字的阶乘是我们使用递归函数 display() 查找的。p>
如果值为 1,则返回 1,因为阶乘为 1。
if (n == 1) return 1;
如果不是,那么如果您想要 5 的值,则将调用递归函数进行以下迭代!
Interation1:5 * display(5 - 1); Interation2:4 * display(4 - 1); Interation3:3 * display(3 - 1); Interation4:4 * display(2 - 1);
以下是递归调用 C# 方法的完整代码。
示例
using System; namespace MyApplication { class Factorial { public int display(int n) { if (n == 1) return 1; else return n * display(n - 1); } static void Main(string[] args) { int value = 5; int ret; Factorial fact = new Factorial(); ret = fact.display(value); Console.WriteLine("Value is : {0}", ret ); Console.ReadLine(); } } }
输出
Value is : 120