最佳答案
                                        
                                                                        
                                我有一个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的同时使用递归?
 
                                
                             
                                
                             
                                
                             
                                
                             
                                
                             
                                
                             
                                
                            