如何让父母控制的所有孩子?

The*_*ask 12 .net c# controls

我正在寻找一个代码示例如何获得父控件的所有子代.

我不知道怎么做.

foreach (Control control in Controls)
{
  if (control.HasChildren)
  {
    ??
  }
}
Run Code Online (Sandbox Code Playgroud)

3Da*_*ave 21

如果您只想要直系孩子,请使用

...
var children = control.Controls.OfType<Control>();
...
Run Code Online (Sandbox Code Playgroud)

如果您想要层次结构中的所有控件(即树中某些控件下的所有控件),请使用:

    private IEnumerable<Control> GetControlHierarchy(Control root)
    {
        var queue = new Queue<Control>();

        queue.Enqueue(root);

        do
        {
            var control = queue.Dequeue();

            yield return control;

            foreach (var child in control.Controls.OfType<Control>())
                queue.Enqueue(child);

        } while (queue.Count > 0);

    }
Run Code Online (Sandbox Code Playgroud)

然后,您可以在表单中使用以下内容:

    private void button1_Click(object sender, EventArgs e)
    {
        /// get all of the controls in the form's hierarchy in a List<>
        foreach (var control in GetControlHierarchy(this))
        {
            /// do something with this control
        }
    }
Run Code Online (Sandbox Code Playgroud)

请注意,__CODE__将立即评估整个Enumerable,这消除了您从协程实现中获得的任何性能优势.