我有一种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>();
}
}
}
这当前会引发“无法转换表达式类型”错误。但是,如果此方法返回 type IEnumerable<Object>
,则代码会构建,但输出中会返回错误的类型。
有没有一种yield return
在使用递归的同时使用的方法?