代码之家  ›  专栏  ›  技术社区  ›  Xami Yen

For循环计数器总是在C#递归函数中重置

  •  0
  • Xami Yen  · 技术社区  · 6 年前

    我有一个奇怪的问题,我没有完全明白。希望有人能解释一下。

    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
            }
        } 
    }
    

    3 回复  |  直到 6 年前
        1
  •  3
  •   Hofma Dresu    6 年前

    您正在创建和设置一个新的方法级变量 loopCounter 在for循环的开头,每次调用函数时。如果要使用类级别变量,应该删除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
    } 
    
        2
  •  1
  •   Ncs    6 年前

        3
  •  1
  •   ThorPF    6 年前

    我认为变量 loopCounter int loopCounter = 1 从for循环。

        4
  •  0
  •   Suraj Rao Raas Masood    4 年前

    如果希望返回递归函数调用的次数,或者换句话说,返回计数,那么这个代码示例将很有帮助。

    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);
        } 
    }