IEnumerable和使用递归的回报收益率 [英] IEnumerable and Recursion using yield return
问题描述
我有一个的IEnumerable< T>我使用要查找一个WebForms的页面控件
法
该方法是递归的,我有返回时的收益回报率
是returnig递归调用的价值我想要的类型存在一些问题。
The method is recursive and I'm having some problems returning the type I want when the yield return
is returnig the value of the recursive call.
我的code如下所示:
My code looks as follows:
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>();
}
}
}
这目前抛出一个无法转换前pression型的错误。然而,如果这个方法返回一个类型的IEnumerable&LT;对象&gt;
中,code建立,但错误的类型返回输出
This currently throws a "Cannot convert expression type" error. If however this method returns type IEnumerable<Object>
, the code builds, but the wrong type is returned in the output.
有没有使用收益回报的一种方式
,同时也使用递归?
Is there a way of using yield return
whilst also using recursion?
推荐答案
在返回的方法的IEnumerable&LT; T&GT;
,收益回报率
必须返回 T
,而不是的IEnumerable&LT; T&GT;
Inside a method that returns IEnumerable<T>
, yield return
has to return T
, not an IEnumerable<T>
.
替换
yield return c.GetDeepControlsByType<T>();
与
foreach (var x in c.GetDeepControlsByType<T>())
{
yield return x;
}
这篇关于IEnumerable和使用递归的回报收益率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!