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

Mas*_*oud 2 c# generics design-patterns if-statement switch-statement

我正在开发一个通用搜索表单,该表单中的搜索控件取决于<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)
}
Run Code Online (Sandbox Code Playgroud)

搜索表单将是这样的

在此输入图像描述

我在表单中使用这些语句来确定每个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);
   ....  
Run Code Online (Sandbox Code Playgroud)

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

Den*_*nis 5

你可以建立某种地图:

更新.

根据你的评论:

    // 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) {}        
Run Code Online (Sandbox Code Playgroud)

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

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

typeToControlsInsertActionMap[propertyType](paramInfo);
Run Code Online (Sandbox Code Playgroud)

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