如何退出递归调用?

How to exit from recursive call?

我有以下递归调用代码。

public string success() 
{
  string status = RecursiveMethod();
  return status;
}

 public string RecursiveMethod()
 {
   string response = "fail";
   if (response =="fail")
   {
     RecursiveMethod();
   }
   return response;
 }

如果响应失败,上面的代码可以正常工作。在连续三次失败后,我将响应值 fail 更改为 success 。在此,RecursiveMethod 函数执行了 3 次,它将以失败响应退出循环。它有什么问题。在我的例子中,如果响应成功,它将退出控件。谁能帮帮我。

嗯,从您的代码中并不清楚响应的实际来源。我将其重构为:

public string RecursiveMethod()
{
    string response = "fail";

    if (someOtherConditionApplies)
        response = "success";

    if (response == "fail")
    {
        response = RecursiveMethod();
    }

    return response;
}

你在某个地方必须确保你

  1. 退出递归
  2. 使用递归调用的结果

然而,我的问题是:为什么在这种情况下使用递归?

向方法添加一个参数,该参数是 Int(或更小的数据类型,如 short 或 byte),默认值为 3,每次它调用自身时,它应该使用值减一来调用。

public string success() 
{
    string status = RecursiveMethod();
    return status;
}

public string RecursiveMethod(int count = 3)
{
    string response = "fail";
    if (response =="fail" && count > 0)
    {
        RecursiveMethod(--count);
    }
    return response;
}

如下更新您的代码并在 CheckStatus 中编写逻辑,这将 return failsuccess

public string success() 
{
  string status = RecursiveMethod();
  return status;
}

 public string RecursiveMethod()
 {
   string response = CheckStatus();
   if (response =="fail")
   {
     RecursiveMethod();
   }
   return response;
 }

string CheckStatus()
{
    //Write Logic on which return "success" or "fail"
}