UserControl Switch

There are two different UserControls that have common properties. I would like to do this in order to switch between them based on an external flag.

UserControl u1, u2;

if(flag)
{
    u1 = u1 as ControlType1;
    u2 = u2 as ControlType1;
}
else
{
    u1 = u1 as ControlType2;
    u2 = u2 as ControlType2;
}

SomeMethod(u1.SelectedItemName, u2.SelectedItemName);

Since UserControl does not have a property called "SelectedItemName", the code will not throw an error.

What I just did, I added an extension method to UserControl that gets "SelectedItemName" using reflection, and I get the value by calling u1.SelectedItemName () instead of u1.SelectedItemName;

My question is an easy way to fix this without using the extension /, possibly the right way. Note that I do not want to repeat SomeMethod (a, b) inside the if statement.

+3
source share
2 answers

, UserControl . , / .

IYourUserControl u1, u2;

SomeMethod(u1, u2);

, SomeMethod :

void SomeMethod(IYourUserControl one, IYourUserControl two) { // ...
+5

isntead:

UserControl u1, u2;

if(flag)
{
    u1 = u1 as ControlType1;
    u2 = u2 as ControlType1;
    SomeMethod((u1 as ControlType1).SelectedItemName, (u2 as ControlType1).SelectedItemName);
}
else
{
    u1 = u1 as ControlType2;
    u2 = u2 as ControlType2;
    SomeMethod((u1 as ControlType2).SelectedItemName, (u2 as ControlType2).SelectedItemName);
}

, BaseControlType, SelectedItemName ControlType1 ControlType2 , :

UserControl u1, u2;

if(flag)
{
    u1 = u1 as ControlType1;
    u2 = u2 as ControlType1;
}
else
{
    u1 = u1 as ControlType2;
    u2 = u2 as ControlType2;
}

SomeMethod((u1 as BaseControlType).SelectedItemName, (u2 as BaseControlType).SelectedItemName);
+3

All Articles