dimanche 4 octobre 2015

How to use Local variable as a type? Compiler said "it is a variable but is used like a type"

I have some code....

in Run-time environment we don`t know what kind of type is v1 variable! For this reason we should write "if else" statement many times!

            if (v1 is ShellProperty<int?>)
            {
                 v2 = (v1 as ShellProperty<int?>).Value;
            }
            else if (v1 is ShellProperty<uint?>)
            {
                 v2 = (v1 as ShellProperty<uint?>).Value;
            }
            else if (v1 is ShellProperty<string>)
            {
                 v2 = (v1 as ShellProperty<string>).Value;
            }
            else if (v1 is ShellProperty<object>)
            {
                 v2 = (v1 as ShellProperty<object>).Value;
            }           

I wrote it 4 times! The difference is only in ShellProperty < AnyType >

So instead of writing this a lot of lines using "if else statement"
I decided to use use Reflection to get property type at run-time!

     Type t1 = v1.GetType().GetProperty("Value").PropertyType;
     dynamic v2 = (v1 as ShellProperty<t1>).Value;

This code can get what kind of PropertyType is v1 and assigns is nicely lo local variable t1.
But after that my compiler says that "t1 is a variable but is used like a type"
So it does not allow me to write t1 inside ShellProperty<>

Please tell me how to solve this problem and How to get more compact code than I have?
Is it necessary to create new class?





Aucun commentaire:

Enregistrer un commentaire