Is there any way to make this code shorter?

//list the controls from the main form foreach (Control c in Controls) { if (c is ComboBox) { ((ComboBox)c).SelectedIndex = -1; } else if (c is TextBox) { ((TextBox)c).Text = ""; } else if (c is CheckBox) { ((CheckBox)c).Checked = false; } //etc. with FIFTY different types to check against } 
+5
source share
3 answers

Use this method to set the properties of your controls:

 public void Set(object obj, string property, object value) { //use reflection to get the PropertyInfo of the property you want to set //if the property is not found, GetProperty() returns null var propertyInfo = obj.GetType().GetProperty(property); //use the C# 6 ?. operator to only execute SetValue() if propertyInfo is not null propertyInfo?.SetValue(obj, value); } 

Name it as follows:

 foreach (Control c in Controls) { Set(c, "SelectedIndex", -1); Set(c, "Text", ""); Set(c, "Checked", false); } 
+6
source

One way is to add three overloaded methods for certain types, drop to dynamic and make these calls:

 foreach (dynamic c in Controls) { ClearOut(c); } ... private static void ClearOut(ComboBox c) { c.SelectedIndex = -1; } private static void ClearOut(TextBox t) { t.Text = string.Empty; } private static void ClearOut(CheckBox c) { c.Checked = false; } 

Since c is dynamic , C # would ClearOut binding of the ClearOut method to runtime, giving you clean code. The disadvantage of this approach is that C # cannot tell you at compile time if one of the overloads is missing.

+9
source

You can create a search for each supported type for an action that clears the controls of this type, then you can add handlers to this search for each supported type:

 public class ControlClearer { private static Dictionary<Type, Action<Control>> lookup = new Dictionary<Type, Action<Control>>(); static ControlClearer() { AddMapping((TextBox control) => control.Text = ""); AddMapping((ComboBox control) => control.SelectedIndex = -1); AddMapping((CheckBox control) => control.Checked = false); } private static void AddMapping<T>(Action<T> clearAction) where T : Control { lookup[typeof(T)] = control => clearAction((T)(object)control); } public static void Clear<T>(T control) where T : Control { //todo support case where T isn't in the dictionary lookup[typeof(T)](control); } public static void Clear(Control control) { //todo support case where the type isn't in the dictionary lookup[control.GetType()](control); } } 
+3
source

Source: https://habr.com/ru/post/1234877/


All Articles