c# - 获取控件类型为 T 的子控件

标签 c#

我有以下函数来获取类型的所有子控件。

    private IEnumerable<Control> GetControlsOfType(Control control, Type type)
    {
        var controls = control.Controls.Cast<Control>();

        return controls.SelectMany(ctrl => GetControlsOfType(ctrl, type))
                                  .Concat(controls)
                                  .Where(c => c.GetType() == type);
    }

我正在尝试使用泛型类型参数对其进行转换。

    private IEnumerable<T> GetControlsOfType<T>(Control control) where T: Control
    {
        var controls = control.Controls.Cast<Control>();

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

代码在.Concat 上有错误.

Error 6 'System.Collections.Generic.IEnumerable<T>' does not contain a definition for 'Concat' and the best extension method overload 'System.Linq.Queryable.Concat<TSource>(System.Linq.IQueryable<TSource>, System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments

如何解决这个问题?

最佳答案

尝试添加 .OfType<Control>()GetControlsOfType<T>(ctrl) 之后而不是你的 Where

所以你的代码是这样的:

return controls.SelectMany(ctrl => GetControlsOfType<T>(ctrl).OfType<Control>())
                                  .Concat(controls)
                                  .OfType<T>();

关于c# - 获取控件类型为 T 的子控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13567875/

相关文章:

c# - Linq 扩展方法 - GetYearWeekFormat 扩展

c# - 使用 CaSTLe Windsor 的 WCF 依赖注入(inject) - 请帮忙?

c# - 将目标框架更改为 .Net Framework 4.0.1 后核心框架类型出现错误

c# - 'ClosedXML.Excel.XLWorkbook' 的类型初始值设定项抛出异常

c# - Sql Server 中的正则表达式

c# - MySQL从c#中的某个用户那里获取关注者

c# - 将类分配给 Html.BeginForm

c# - Windows 7 跳转列表(Windows 窗体,C#)

c# - 启动、停止线程

c# - 比较两个日期的最有效方法;一个有时间,一个没有