这是递归还是迭代?
如果你看一下,它正在调用底部(内部)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;
}
}
}
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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该方法是递归的,因为它在第 9 行调用自身。它还使用迭代(
foreach
循环)。它也是惰性的,因为它产生结果,所以除非调用者循环遍历枚举器,否则什么都不会执行。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:
For example:
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.