清除C#表单上所有控件的最佳方法是什么?

Nat*_*n W 14 c# controls

我记得有一段时间以前看到有人问过这些问题,但是我做了搜索而找不到任何东西.

我正在尝试用最干净的方法将表单上的所有控件清除回默认值(例如,清除文本框,取消选中复选框).

你会怎么做?

Nat*_*n W 17

到目前为止我想出的是这样的:

public static class extenstions
{
    private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() { 
            {typeof(TextBox), c => ((TextBox)c).Clear()},
            {typeof(CheckBox), c => ((CheckBox)c).Checked = false},
            {typeof(ListBox), c => ((ListBox)c).Items.Clear()},
            {typeof(RadioButton), c => ((RadioButton)c).Checked = false},
            {typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},
            {typeof(Panel), c => ((Panel)c).Controls.ClearControls()}
    };

    private static void FindAndInvoke(Type type, Control control) 
    {
        if (controldefaults.ContainsKey(type)) {
            controldefaults[type].Invoke(control);
        }
    }

    public static void ClearControls(this Control.ControlCollection controls)
    {
        foreach (Control control in controls)
        {
             FindAndInvoke(control.GetType(), control);
        }
    }

    public static void ClearControls<T>(this Control.ControlCollection controls) where T : class 
    {
        if (!controldefaults.ContainsKey(typeof(T))) return;

        foreach (Control control in controls)
        {
           if (control.GetType().Equals(typeof(T)))
           {
               FindAndInvoke(typeof(T), control);
           }
        }    

    }

}
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样调用扩展方法ClearControls:

 private void button1_Click(object sender, EventArgs e)
    {
        this.Controls.ClearControls();
    }
Run Code Online (Sandbox Code Playgroud)

编辑:我刚刚添加了一个通用的ClearControls方法,它将清除该类型的所有控件,可以像这样调用:

this.Controls.ClearControls<TextBox>();
Run Code Online (Sandbox Code Playgroud)

目前它只处理顶级控件,不会通过组框和面板进行挖掘.