对于循环计数器始终在 C# 递归函数中重置



我有一个奇怪的问题,我没有完全理解它。希望有人能对此有所了解。

我在递归函数中有一个 for 循环,即使循环计数器是类的实例变量,它也总是被重置。 为什么?这是代码:

public class Products{
private int loopCounter=1;
private int loop=10;
public int ProductCount {get;set;}
public int GetProducts(int Take, int Skip)
{
//code that sets ProductCount is removed
for (int loopCounter = 1; loopCounter < loop; loopCounter++)
{
//Depending on ProductCount, Take and Skip values are
//computed and passed to GetProducts. This code removed for brevity and am hard coding them
GetProducts(10,5);
//code to process GetProducts output removed
}
} 
}

由于我不明白的原因,loopCounter 总是被重置为 1,并且循环永远持续下去。循环不应该在 10 次迭代后停止吗?

每次调用函数时,您都会在 for 循环的开头创建和设置一个新的方法级变量loopCounter。如果要使用类级别变量,则应删除 for 循环的第一部分(类似于for(; loopCounter < loop; loopCounter++)

也就是说,我不建议使用循环来控制这样的递归。最好只使用循环,或者在遇到边界条件时让 GetProducts 返回。

public class Products{
private int loopCounter=1;
private int loop=10;
public int ProductCount {get;set;}
public int GetProducts(int Take, int Skip)
{
if(loopCounter >= loop) return;
loopCounter++;
//code that sets ProductCount is removed
//Depending on ProductCount, Take and Skip values are
//computed and passed to GetProducts. This code removed for brevity and am hard coding them
GetProducts(10,5);
//code to process GetProducts output removed
} 

我可能会对循环中除了 GetProducts(( 之外的实际内容感到有些困惑,但似乎您没有停止的条件。从 1 开始运行一次循环,然后再次调用该函数,并创建一个从 1 开始的新循环。您需要创建一个条件来停止此无限调用机制,以便它将返回到现有的调用。

我认为变量loopCounter与全局变量不同,并且每次调用函数时都会创建一个新变量,请尝试从 for 循环中删除以下内容:int loopCounter = 1

如果要返回递归函数调用的数量,或者换句话说,Count,那么此代码示例将有所帮助。

public class Products{

public int GetProducts(int Take)
{
// Check if you are ready to return the count.
if (/* Some condition to check. */)
{
// Returned value will be 0, if you don't call method
// recursive, which is equivalent to counter == 0.
return 0;
}

// Do some stuff here and get result.
// Returned value will be 1 + next value of the Method
// call, which is whether 0 or 1 if recursion goes further.
// All together, the end value will be the count of
// recursive method calls.
return 1 + GetProducts(result);
} 
}

最新更新