c# - 避免使用 if-else 或 switch-case 语句来进行决定

标签 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用于决定为每种属性类型设置哪些适当的控制?

最佳答案

您可以构建某种 map :

更新

根据您的评论:

    // 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>是一个委托(delegate),它根据属性类型插入适当的控件:

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

typeToControlsInsertActionMap[propertyType](paramInfo);

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

关于c# - 避免使用 if-else 或 switch-case 语句来进行决定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17140522/

相关文章:

c# - 从不同线程调用方法

Android 仪表板图标大小

mvvm - MVVM View 模型的结构设计模式?

java - Java 中用于获取输入并对其执行操作的设计模式

c# - 使用 Exchange Web 服务创建具有默认签名的新邮件

c# - 如何从按钮单击调用 Gridview 单元格单击事件

c# - 结合泛型方法和重载

java - 列表中列表的特定通用类型

c# - 在用户控件中包含 Css 文件

c# - 装饰器设计模式 : What is meant by adding functionality?