这是递归还是迭代?

Jor*_*dan 4 c# iteration recursion

如果你看它在底部(内部)foreach语句中调用FindChildControls方法,因为它来自foreach,是否会使它递归或迭代?

谢谢!

public static IEnumerable<T> FindChildControls<T>(this ControlCollection controlCollection) where T: class 
{
  foreach(Control control in controlCollection)
  {
    if(control is T)
    {
      yield return control as T;  
    }
    foreach(T type in control.Controls.FindChildControls<T>())  
    {  
      yield return type;  
    }  
  }   
} 
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 11

这个方法是递归的,因为它在第9行调用它自己.它也使用迭代(foreach循环).它也是懒惰的,因为它会产生结果,所以除非调用者遍历枚举器,否则什么都不会执行.

  • @Tim,不,不是.这是`ControlCollection`类的扩展方法,我打赌5个生啤酒,`control.Controls`是一个`ControlCollection`. (3认同)

Eri*_*ert 8

这是你如何识别递归方法.每个写得很好的递归方法都有相同的基本形状:

Method(Arguments) --> Result
    If Arguments are easy
        Return the easy result
    Else
        Make arguments for a simpler version of the problem
        Call Method one or more times with those arguments
        Combine the results and return the combined result
Run Code Online (Sandbox Code Playgroud)

例如:

static int Height(Tree t)
{
    if (t == null) 
        return 0;
    else
    {
        int leftHeight = Height(t.Left);
        int rightHeight = Height(t.Right);
        return Math.Max(leftHeight, rightHeight) + 1;
    } 
}
Run Code Online (Sandbox Code Playgroud)

经典的递归函数.首先,确定我们是否处于基本情况,这种情况不能进一步减少.如果我们是,那很好.如果没有,找到一个或多个较小的问题,递归地解决它们,然后将它们的结果合并到这个问题的结果中.

你的方法显然是递归的.它首先检查它是否在基本情况下.基本情况是参数没有子控件,在这种情况下,它返回一个包含自身的序列,或者返回一个空序列.递归的情况是参数具有子控件,在这种情况下,它通过计算子项的结果并将其与参数本身的结果相结合来返回结果.有一个基本案例和一个递归案例,可以将问题减少到自身的较小版本,因此它是一种递归方法.