将我表单中的所有按钮添加到列表中

Add all buttons from my form to a list

我的 windows 表单中有 86 个按钮。我在我的代码中制作了一个按钮列表。现在我想将所有按钮添加到列表中。有没有办法一次将所有按钮添加到列表中,还是我需要一个按钮一个按钮地添加所有按钮?

这是我的清单:List<Button> lColors = new List<Button>();

如果所有按钮都在表单上(例如不在 Panel 中)

List<Button> lColors = this.Controls.OfType<Button>().ToList();

如果一些按钮在表单上而一些在面板中

List<Button> lColors = this.Controls.OfType<Button>()
               .Concat(this.panel1.Controls.OfType<Button>())
               .ToList();

您可以使用以下递归方法获取指定控件的指定类型的所有子控件:

private static IEnumerable<T> GetAllControls<T>(Control control)
{
    var controls = control.Controls.OfType<T>();
    return control.Controls.Cast<Control>()
        .Aggregate(controls, (current, c) => current.Concat(GetAllControls<T>(c)));
}

用法:

var buttons = GetAllControls<Button>(this);