C# 通过反射获取Winform/UserControl中的所有复选框

C# 通过反射获取Winform/UserControl中的所有复选框,c#,winforms,reflection,user-controls,C#,Winforms,Reflection,User Controls,我想添加一个动态的CheckAll()方法来检查类中声明的所有复选框 我尝试了以下代码: class MyContol : UserControl { /// /// HIDDEN but there is plenty of checkboxes declaration /// private void CheckAll() { FieldInfo[] props = this.GetType().GetFields(); foreach (Field

我想添加一个动态的
CheckAll()
方法来检查类中声明的所有复选框

我尝试了以下代码:

class MyContol : UserControl
{
  ///
  ///  HIDDEN but there is plenty of checkboxes declaration
  ///

  private void CheckAll()
  {
    FieldInfo[] props = this.GetType().GetFields();

    foreach (FieldInfo p in props)
    {
      if (p.FieldType is CheckBox)
      {
         /// TODO: Check my box
      }
    }
  }
}
。。。但是
props
是空的。我不知道如何定位使用designer部件制作的复选框


您知道如何使用“反射”来定位“设计视图”组件添加的目标吗?

控件的复选框都应该是子控件。也就是说,它们是
控件.Controls
集合中的子对象(或者可能是子对象的子对象)。此外,控件不必将它们作为类的属性或字段进行引用。例如,我可以使用
myControl.Controls.add(new checkbox())
向现有控件添加复选框。因此,在这里你不需要思考,也不会真正得到你想要的东西——如果我理解正确的话

尝试以这种方式枚举它们(要检查面板中的示例控件,需要执行递归搜索):


默认情况下,UserControl上的控件是私有字段,因此我想您应该提供非公共标志作为GetFields方法中绑定属性的参数。请尝试以下操作:

this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic);

但是你不需要通过反思来实现你在这里想要的东西。

我使用@Sayse,非常有趣
全选(c)很好,我知道,但最后我更喜欢lc引入的解决方案。正如你所说,没有反射
this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic);