避免使用if-else或switch-case语句进行决策

时间:2013-06-17 04:42:49

标签: c# design-patterns generics if-statement switch-statement

我正在开发一个通用搜索表单,该表单中的搜索控件取决于<T>属性的类型,例如,如果T为Order

public class Order
{
   public string OrderNumber {get; set;} // search control is 1 TextBox
   public decimal OrderWeight {get; set;} // search controls are 2 TextBox (for accepting a range)
}

搜索表单将是这样的

enter image description here

我在表单中使用了这些语句来确定每个T属性的适当控件:

if (propertyType.Name == "System.String")
   InsertOneTextBox(paramInfo);
else 
   if(propertyType.Name == "System.Int32" || propertyType.Name == "System.Decimal") 
      InsertTwoTextBoxs(paramInfo);
   else
    if(propertyType.Name == "System.DateTime") 
      InsertTwoDateTimePickers(paramInfo);
    else
       if(propertyType.Name == someotherconditions)    
          InsertOneComboBox(paramInfo);
   ....  

是否有任何最佳做法可以避免使用if elseswitch case来确定为每种属性类型设置的适当控件?

2 个答案:

答案 0 :(得分:5)

您可以构建某种地图:

<强> UPD

根据你的评论:

    // somewhere this class is defined in your code
    class ParamInfo {}

    private readonly Dictionary<Type, Action<ParamInfo>> typeToControlsInsertActionMap;

    public MyForm()
    {
        typeToControlsInsertActionMap = new Dictionary<Type, Action<ParamInfo>>
        {
            { typeof(string), InsertOneTextBox },
            { typeof(int), InsertTwoTextBoxs },
            { typeof(decimal), InsertTwoTextBoxs },

            // etc.
        };
    }

    private void InsertOneTextBox(ParamInfo paramInfo) {}
    private void InsertTwoTextBoxs(ParamInfo paramInfo) {}        

此处Action<ParamInfo>是一个委托,根据属性类型插入适当的控件:

var paramInfo = // ...
var propertyType = // ...    

typeToControlsInsertActionMap[propertyType](paramInfo);

请注意,您不应在案例中检查类型名称。请改用typeof运算符。

答案 1 :(得分:0)

使用TinyType创建一个类,并使输入字符串强类型化。基于这些输入创建4个策略(谈论策略模式),所有策略都来自同一界面。创建一个Factory类,并在您的类中注入您需要这些策略的位置。现在在你的类中注入这个工厂让你的字符串输入和工厂决定你想要做什么样的插入(一个文本框/ 2个文本框等)