我有一个IEnumerable<T>方法,我正在使用它来查找WebForms页面中的控件。
这个方法是递归的,当yield return返回递归调用的值时,我在返回我想要的类型时遇到了一些问题。
我的代码如下:
public static IEnumerable<Control> GetDeepControlsByType<T>(this Control control)
{
foreach(Control c in control.Controls)
{
if (c is T)
{
yield return c;
}
if(c.Controls.Count > 0)
{
yield return c.GetDeepControlsByType<T>();
}
}
}
当前抛出“无法转换表达式类型”错误。但是,如果此方法返回类型IEnumerable<Object>,则构建代码,但在输出中返回错误的类型。
有没有一种方法可以在使用递归的同时使用收益率?
Seredynski的语法是正确的,但是您应该注意避免在递归函数中使用yield return,因为这对于内存使用来说是一场灾难。参见https://stackoverflow.com/a/3970171/284795,它会随着深度而爆炸性地扩展(在我的应用程序中,类似的函数使用了10%的内存)。
一个简单的解决方案是使用一个列表,并将递归https://codereview.stackexchange.com/a/5651/754传递给它
/// <summary>
/// Append the descendents of tree to the given list.
/// </summary>
private void AppendDescendents(Tree tree, List<Tree> descendents)
{
foreach (var child in tree.Children)
{
descendents.Add(child);
AppendDescendents(child, descendents);
}
}
或者,您可以使用堆栈和while循环来消除递归调用https://codereview.stackexchange.com/a/5661/754
Seredynski的语法是正确的,但是您应该注意避免在递归函数中使用yield return,因为这对于内存使用来说是一场灾难。参见https://stackoverflow.com/a/3970171/284795,它会随着深度而爆炸性地扩展(在我的应用程序中,类似的函数使用了10%的内存)。
一个简单的解决方案是使用一个列表,并将递归https://codereview.stackexchange.com/a/5651/754传递给它
/// <summary>
/// Append the descendents of tree to the given list.
/// </summary>
private void AppendDescendents(Tree tree, List<Tree> descendents)
{
foreach (var child in tree.Children)
{
descendents.Add(child);
AppendDescendents(child, descendents);
}
}
或者,您可以使用堆栈和while循环来消除递归调用https://codereview.stackexchange.com/a/5661/754