我有一个 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>
,则代码可以构建,但输出的类型不正确。
是否有一种方法可以在使用递归的同时使用yield return
?
if(c.Controls.Count > 0)
-->if(c.Controls.Any())
,特别是如果你也在使用yield :) - tymtamyield return
,因为内存使用会呈指数级增长。请参考 https://dev59.com/bHI95IYBdhLWcg3w_zas#30300257。 - Colonel Panic