我正在开发一个通用搜索表单,该表单中的搜索控件取决于 <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)
}
搜索表单将是这样的
我在表单中使用了这些语句来决定每个 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
或switch
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/