c# - 通用所有控件方法

标签 c# winforms linq generics

想不出更好的标题,所以很抱歉..

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

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 抛出

Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable<T>' to 'System.Linq.ParallelQuery<System.Windows.Forms.Control>'

最佳答案

问题是 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>()));
}

关于c# - 通用所有控件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17454389/

相关文章:

c# - 在某些平台上使用 odbc 时出错(32 位与 64 位)

c# - 计算物体摩擦力时不准确

.net - ControlStyles.DoubleBuffer 与 ControlStyles.OptimizedDoubleBuffer

c# - 执行自定义查询—— Entity Framework

linq - 响应式(Reactive)扩展 - Observable.FromEvent 类型转换

快速计算大字符串之间距离的 C# 代码或算法?

c# - 列表的通用列表,将 List<List<T>> 转换为 IList<IList<T>>

c# - certMgr.exe 未在个人本地计算机存储中加载证书私钥 (Windows 10)

c# - 如何防止 DGV 隐藏顶行?

c# - 使用 LINQ 时 VB TryCast 和 C# "as"运算符的区别