Reputation: 8171
I'm developing a generic search form, that search controls in that form are depends on type of <T>
properties, for example if T is 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)
}
the search form will be something like this
i used this statements in my form for deciding that what are appropriate controls for each T
property:
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);
....
is there any best practice for avoid using if
else
s or switch
case
for deciding that what are appropriate controls set for each property type?
Upvotes: 2
Views: 1250
Reputation: 312
Create a class using TinyType and make your input string strong typed. Based on these inputs create 4 strategies ( Talking about Strategy Pattern) all driving from same interface. Create a Factory class and inject in your class where you need these strategies. Now inject this factory in your class let your stringtyped input and factory decide what kind of insertion you want to do ( one text box/ 2 text box etc.)
Upvotes: 0
Reputation: 37770
You can build some kind of map:
Upd.
According to your comment:
// 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) {}
Here Action<ParamInfo>
is a delegate, which inserts appropriate controls, depending on property type:
var paramInfo = // ...
var propertyType = // ...
typeToControlsInsertActionMap[propertyType](paramInfo);
Note, that you shouldn't check type name in your case. Use typeof
operator instead.
Upvotes: 5