Reputation: 1243
i am developing a windows application and in that i created a class for common look and feel setting
CommonAppearance class Code :
static void SetCommonAppearance(Label ctrl){ //some appearance setting code}
static void SetCommonAppearance(GridGroupingControl ctrl){ //some appearance setting code}
static void SetCommonAppearance(GradientPanel ctrl){ //some appearance setting code}
static void SetCommonAppearance(Form ctrl){ //some appearance setting code}
static void SetCommonAppearance(ComboBox ctrl){ //some appearance setting code}
static void SetCommonAppearance(CheckBox ctrl){ //some appearance setting code}
static void SetCommonAppearance(RadioButton ctrl){ //some appearance setting code}
static void SetCommonAppearance(Button ctrl){ //some appearance setting code}
public static void UseCommonTheme(Form form)
{
List<Control> lstControls = GetAllControls(form.Controls);
foreach (Control ctr in lstControls)
{
string temp2 = ctr.GetType().Name;
switch (temp2)
{
case "TextBox":
SetCommonAppearance((TextBox)ctr);
break;
case "AutoLabel":
SetCommonAppearance((Label)ctr);
break;
case "GridGroupingControl":
SetCommonAppearance((GridGroupingControl)ctr);
break;
case "ButtonAdv":
ApplyCustomTheme((ButtonAdv)ctr);
break;
case "CheckBoxAdv":
SetCommonAppearance((CheckBox)ctr);
break;
case "ComboBoxAdv":
SetCommonAppearance((ComboBox)ctr);
break;
case "RadioButtonAdv":
SetCommonAppearance((RadioButton)ctr);
break;
}
}
}
this is acceptable when there are less control application to set common appearance but in my application there are number of different type of controls are used.
In the method UseCommonTheme(Form form)
instead of using switch case Can we use reflection to cast the controls ? somthing like
foreach (Control ctr in lstControls)
{
string controlType = ctr.GetType().Name;
SetCommonAppearance((class reference of 'controlType')ctr);
}
Thanks in advance.
Upvotes: 0
Views: 176
Reputation: 15941
If you are using .net 4 you can take advantage of the dlr (dynamic language runtime):
foreach (dynamic ctr in lstControls)
{
SetCommonAppearance(ctr);
}
The dlr will resolve the correct overload for you.
If you want to use reflection:
var type = typeof(CommonAppearance);
var methods = type.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
foreach (Control ctr in lstControls)
{
var setAppearanceMethod =
methods.FirstOrDefault(m => m.GetParameters()[0].ParameterType == ctr.GetType());
if(setAppearanceMethod!=null)
setAppearanceMethod.Invoke(null, new[] { ctr });
}
Upvotes: 3