开发者

Is this Recursive or Iteration?

if you look it is calling the method FindChildControls in the bottom (inner)foreach statement, since it is coming from a foreach does that make it recursive or iterative?

Thanks!

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


This method is recursive because it calls itself on line 9. It also uses iterations (foreach loops). It's also lazy as it yields results, so unless the caller loops through the enumerator nothing will execute.


Here's how you recognize recursive methods. Every well-written recursive method has the same basic shape:

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

For example:

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

A classic recursive function. First, determine if we are in the base case, the case that cannot be reduced further. If we are, great. If not, find one or more smaller problems, solve them recursively, and then combine their results into the result to this problem.

Your method is clearly recursive. It begins by checking to see if it is in the base case. The base case is that the argument has no child controls, in which case it either returns a sequence containing itself, or it returns an empty sequence. The recursive case is that the argument has child controls, in which case it returns a result by computing the results from the children and combining that with the result from the argument itself. There is a base case and a recursive case which reduces the problem to smaller versions of itself, so it is a recursive method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜