I have a code ...
in the run-time environment, we donβt know what type the variable v1 is! For this reason, we must write "if else" 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 only difference is ShellProperty <AnyType>
Therefore, instead of writing this many lines using "if else statement"
I decided to use Reflection to get the type of the property at runtime!
Type t1 = v1.GetType().GetProperty("Value").PropertyType; dynamic v2 = (v1 as ShellProperty<t1>).Value;
This code can get what type of PropertyType is v1, and assignment is a good local variable t1.
But after that, my compiler says that "t1 is a variable, but is used as a type"
Therefore, it does not allow me to write t1 inside ShellProperty <>
Please tell me how to solve this problem and how to get a more compact code than me?
Do I need to create a new class?
source share