3

想不出更好的标题,所以请原谅..

我正在尝试将此方法(它将检索表单的所有子控件)转换为扩展方法并接受接口作为输入。到目前为止,我最多

public IEnumerable<Control> GetAll<T>(this Control control) where T : class
{
    var controls = control.Controls.Cast<Control>();

    return controls.SelectMany(ctrl => GetAll<T>(ctrl))
                                .Concat(controls)
                                .Where(c => c is T);
}

这工作正常,除了我需要OfType<T>()在调用它时添加以访问它的属性。

例如(这个 == 形式)

this.GetAll<IMyInterface>().OfType<IMyInterface>()

我正在努力将返回类型转换为通用返回类型IEnumerable<T>,这样我就不必包含一个OfType只会返回相同结果但正确转换的返回类型。

有人有什么建议吗?

(将返回类型更改为IEnumerable<T>导致Concat抛出

实例参数:无法从“System.Collections.Generic.IEnumerable <T>”转换为“System.Linq.ParallelQuery <System.Windows.Forms.Control>

4

1 回答 1

3

问题是它Concat也想要一个IEnumerable<T>- 而不是IEnumerable<Control>. 这应该可以工作:

public static IEnumerable<T> GetAll<T>(this Control control) where T : class
{
    var controls = control.Controls.Cast<Control>();

    return controls.SelectMany(ctrl => GetAll<T>(ctrl))
                                .Concat(controls.OfType<T>()));
}
于 2013-07-03T17:28:08.550 回答