解决方法
到目前为止我所提到的是这样的:
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); } } } }
private void button1_Click(object sender,EventArgs e) { this.Controls.ClearControls(); }
编辑:我刚刚添加了一个通用的ClearControls方法,将清除该类型的所有控件,可以这样调用:
this.Controls.ClearControls<TextBox>();
目前它只会处理顶级控件,而不会通过组框和面板进行挖掘.