如何退出递归调用?



我有以下用于递归调用的代码。

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

如果响应失败,上述代码将正常工作。连续三次失败后,我将响应值 fail 更改为成功。在这种情况下,递归方法函数执行三次,它将退出循环并发出失败响应。这有什么问题。就我而言,如果响应成功,它将退出控件。任何人都可以尝试帮助我。

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

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

你必须在某个地方确保你

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

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

向方法添加一个参数,该参数是 Int(或较小的数据类型,如短整型或字节(,默认值为 3,每次调用自身时都应使用值减 1 进行调用。

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 中编写逻辑,该逻辑将返回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"
}

最新更新