有没有办法让这段代码更短?

时间:2015-10-30 17:09:42

标签: c#

//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
}

3 个答案:

答案 0 :(得分:9)

一种方法是为特定类型添加三个重载方法,转换为dynamic,并进行如下调用:

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;
}

由于cdynamic,C#会推迟ClearOut方法绑定到运行时,为您提供外观整洁的代码。这种方法的缺点是,如果缺少其中一个重载,C#无法在编译时告诉你。

答案 1 :(得分:6)

使用此方法设置控件的属性:

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);
}

这样称呼:

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

答案 2 :(得分:3)

您可以创建从每个受支持的类型到清除该类型控件的操作的查找,然后可以为每个支持的类型的查找添加处理程序:

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);
    }
}