IEnumerable 和 Recursion 使用 yield return [英] IEnumerable and Recursion using yield return

查看:32
本文介绍了IEnumerable 和 Recursion 使用 yield return的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 IEnumerable 方法,我用它来查找 WebForms 页面中的控件.

I have an IEnumerable<T> method that I'm using to find controls in a WebForms page.

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

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.

我的代码如下:

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,则代码会生成,但输出中会返回错误的类型.

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.

有没有办法在使用 yield return 的同时还使用递归?

Is there a way of using yield return whilst also using recursion?

推荐答案

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

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 和 Recursion 使用 yield return的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆