查找组件非Visual C#

时间:2014-11-19 20:29:00

标签: c# winforms

我已经尝试了很多方法来列出表单的所有非可视组件,例如OpenDialog,ImageList,TableAdapters等,但找不到任何东西。为了找到屏幕上的控件,我在“控件”屏幕中使用Foreach进行了管理,但对于那些非可视组件,我什么也没找到。我使用下面的代码但没有成功:

private IEnumerable<Component> EnumerateComponents()
{
    return from field in GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
           where typeof (Component).IsAssignableFrom(field.FieldType)
           let component = (Component) field.GetValue(this)
           where component != null
           select component;
}

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

private IEnumerable<Component> EnumerateComponents()
{
    return this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
           .Where(f => typeof(Component).IsAssignableFrom(f.FieldType))
           .Where(f => !typeof(Control).IsAssignableFrom(f.FieldType))
           .Select(f => f.GetValue(this))
           .OfType<Component>();
}
相关问题