【问题标题】:Avoid if-else or switch-case statements for deciding避免使用 if-else 或 switch-case 语句进行决定
【发布时间】:2013-06-17 04:42:48
【问题描述】:

我正在开发一个通用搜索表单,该表单中的搜索控件取决于 <T>properties 的类型,例如,如果 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)
}

搜索表单会是这样的

我在我的表单中使用了这个语句来决定每个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 elses 或 switch case 来决定为每种属性类型设置哪些适当的控件?

【问题讨论】:

  • 您能在if-else 示例中放置大括号吗?
  • @IAbstract:我编辑了帖子。

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


【解决方案1】:

您可以构建某种地图:

更新

根据您的评论:

    // 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&lt;ParamInfo&gt; 是一个委托,它根据属性类型插入适当的控件:

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

typeToControlsInsertActionMap[propertyType](paramInfo);

请注意,您不应该在您的情况下检查类型名称。请改用typeof 运算符。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 2022-08-23
      相关资源
      最近更新 更多