简体   繁体   English

C#中的递归返回类型

[英]Return Type for recursion in c#

Which return type should we use in c#?Is recursion possible using the "void" return type in c#? 我们应该在c#中使用哪种返回类型?可以在c#中使用“无效”返回类型进行递归吗?

I have a function in which return type is a void, but when I call it, it recursively undergoes Infinite looping, so what is better solution for this: 我有一个其中返回类型为void的函数,但是当我调用它时,它递归地进行了无限循环,因此对此有更好的解决方案:

I am using function as stated below: 我正在使用如下所述的功能:

void A()
{
  //Some code
  A()
}

I think your understanding of recursion needs some sharpening. 我认为您对递归的理解需要加强。

Have a closer look at Recursion 仔细看看递归

Despite the usefulness of recursion, you can easily create a recursive function that never returns a result and cannot reach an endpoint. 尽管递归很有用,您仍可以轻松创建一个递归函数,该函数从不返回结果且无法到达端点。 Such a recursion causes the computer to execute an infinite loop. 这样的递归导致计算机执行无限循环。

Another problem that can occur with recursion is that a recursive function can use all the available resources (such as system memory and stack space). 递归可能发生的另一个问题是递归函数可以使用所有可用资源(例如系统内存和堆栈空间)。 Each time a recursive function calls itself (or calls another function that calls the original function), it uses some resources. 递归函数每次调用自身(或调用另一个调用原始函数的函数)时,都会使用一些资源。 These resources are freed when the recursive function exits, but a function that has too many levels of recursion may use all the available resources. 当递归函数退出时,这些资源将被释放,但是递归级别过多的函数可能会使用所有可用资源。 When this happens, an exception is thrown. 发生这种情况时,将引发异常。

Your issue here is not the return type. 您的问题不是返回类型。 You need to have some rule for the resursion to end, lets say a depth of recustion call, or a number of directories as a max to recurs. 您需要有一些规则来终止递归,可以说是一个深度的拒绝调用,或者是有多个目录作为递归的最大值。

Maybe also have a look at Recursive methods using C# 也许还可以看看使用C#的递归方法

Every recursive method sequence must be somehow terminated. 每个递归方法序列都必须以某种方式终止。 Often the first part of the recursive method will have a branch that tests for a condition being met. 通常,递归方法的第一部分将有一个分支,用于测试是否满足条件。 In this way, the recursive methods continue until the result is attained. 以这种方式,递归方法继续进行直到获得结果。 for example 例如

static int Recursive(int value)
    {       
    if (value >= 10)
    {
        // throw new Exception("End");
        return value;
    }
    return Recursive(value + 1);
    }

There is nothing to do with the return type. 与返回类型无关。 if conditions are not supplied your function will go to infinite loop 如果没有提供条件,您的函数将进入无限循环

As you are calling the same function, it is obvious it will go in infinite loop. 当您调用相同的函数时,很明显它将进入无限循环。 After a condition is satisfied you need to come out of this loop and that can be achieved by using break keyword. 满足条件后,您需要退出此循环,这可以通过使用break关键字来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM