首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用yield的IEnumerable和递归

使用yield的IEnumerable和递归
EN

Stack Overflow用户
提问于 2010-01-13 18:26:21
回答 5查看 81.3K关注 0票数 327

我有一个用于在WebForms页面中查找控件的IEnumerable<T>方法。

这个方法是递归的,当yield return返回递归调用的值时,我在返回我想要的类型时遇到了一些问题。

我的代码如下所示:

代码语言:javascript
复制
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

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-01-13 18:29:50

在返回IEnumerable<T>的方法中,yield return必须返回T,而不是IEnumerable<T>

替换

代码语言:javascript
复制
yield return c.GetDeepControlsByType<T>();

通过以下方式:

代码语言:javascript
复制
foreach (var x in c.GetDeepControlsByType<T>())
{
  yield return x;
}
票数 504
EN

Stack Overflow用户

发布于 2013-08-11 22:38:30

其他人给你提供了正确的答案,但我不认为你的案例从让步中受益。

下面是一个代码片段,它可以在不让步的情况下实现相同的效果。

代码语言:javascript
复制
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>()));
}
票数 19
EN

Stack Overflow用户

发布于 2010-01-13 18:32:02

我认为你必须返回枚举中的每个控件。

代码语言:javascript
复制
    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;
                }
            }
        }
    }
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2055927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档