我有一个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>();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这当前抛出"无法转换表达式类型"错误.但是IEnumerable<Object>,如果此方法返回类型,则代码构建,但输出中返回错误的类型.
有没有使用yield return同时也使用递归的方法?