如何在整个控件链中找到类型控件?

时间:2017-12-18 14:23:21

标签: c# winforms controls

我想在我的表单中找到实现某个界面的所有控件(让我们说ITestInterface)。我试过这个:

this.Controls.OfType<ITestInterface>();

但它只有一个级别(尽管在MSDN - @dasblinkenlight中写了什么),所以如果例如,我在表单中有一个面板并且ITestInterface控件在面板内部,它找不到它。

怎么做?

编辑:正如@HansPassant在评论中写道,我可以硬编码我的面板名称,但是,我需要一个通用的解决方案,而不是特定形式的特定解决方案。

1 个答案:

答案 0 :(得分:2)

您必须使用递归并逐步执行控件的Controls属性:

private IEnumerable<T> GetAllOfType<T>(Control rootControl)
{
    return rootControl.Controls.OfType<T>().
           Concat(rootControl.Controls.OfType<Control>().SelectMany(GetAllOfType<T>));

}

你可以使用它:

var allOfTestInterface = GetAllOfType<ITestInterface(this);

使用该接口的所有控件直接包含在根控件中(使用OfType<>()调用),然后再次为该控件包含的所有控件调用该方法,从而递归所有容器。 SelectMany将此嵌套列表展平为一个列表。