我有一个用于在WebForms页面中查找控件的IEnumerable<T>
方法。
这个方法是递归的,当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
?
发布于 2010-01-13 18:29:50
在返回IEnumerable<T>
的方法中,yield return
必须返回T
,而不是IEnumerable<T>
。
替换
yield return c.GetDeepControlsByType<T>();
通过以下方式:
foreach (var x in c.GetDeepControlsByType<T>())
{
yield return x;
}
发布于 2013-08-11 22:38:30
其他人给你提供了正确的答案,但我不认为你的案例从让步中受益。
下面是一个代码片段,它可以在不让步的情况下实现相同的效果。
public static IEnumerable<Control> GetDeepControlsByType<T>(this Control control)
{
return control.Controls
.Where(c => c is T)
.Concat(control.Controls
.SelectMany(c =>c.GetDeepControlsByType<T>()));
}
发布于 2010-01-13 18:32:02
我认为你必须返回枚举中的每个控件。
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)
{
foreach (Control childControl in c.GetDeepControlsByType<T>())
{
yield return childControl;
}
}
}
}
https://stackoverflow.com/questions/2055927
复制相似问题