Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 避免使用if-else或switch-case语句进行判断_C#_Design Patterns_Generics_If Statement_Switch Statement - Fatal编程技术网

C# 避免使用if-else或switch-case语句进行判断

C# 避免使用if-else或switch-case语句进行判断,c#,design-patterns,generics,if-statement,switch-statement,C#,Design Patterns,Generics,If Statement,Switch Statement,我正在开发一个通用搜索表单,该表单中的搜索控件取决于属性的类型,例如,如果T是顺序 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是
顺序

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
else
s或
开关
case
来决定为每个属性类型设置哪些适当的控件的最佳做法?

您可以构建某种映射:

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

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

使用TinyType创建一个类,并使输入字符串强类型化。根据这些输入创建4个策略(谈论策略模式),所有策略都来自同一界面。创建一个工厂类,并在需要这些策略的地方注入类。现在将这个工厂注入到类中,让您的stringtyped输入和工厂决定您要执行的插入类型(一个文本框/2个文本框等)

您能在
if else
示例中放置大括号吗?@IAbstract:我编辑了这篇文章。
var paramInfo = // ...
var propertyType = // ...    

typeToControlsInsertActionMap[propertyType](paramInfo);