How to use local variable as a type? Compiler says “it is a variable but is used like a type”

前端 未结 2 1157
Happy的楠姐
Happy的楠姐 2020-12-03 10:16

At run-time, I don\'t know what type of variable v1 is. For this reason, I wrote many if else statements:

if (v1 is ShellProperty         


        
2条回答
  •  广开言路
    2020-12-03 10:33

    You were very close, you were just missing a call to MakeGenericType.

    I believe your code would look like the following:

    Type t1 = v1.GetType().GetProperty("Value").PropertyType;
    var shellPropertyType = typeof(ShellProperty<>);
    var specificShellPropertyType = shellPropertyType.MakeGenericType(t1);
    dynamic v2 = specificShellPropertyType.GetProperty("Value").GetValue(v1, null);
    

    Edit: As @PetSerAl pointed out I added some layers of indirection that were unnecessary. Sorry OP, you probably want a one liner like:

    dynamic v2 = v1.GetType().GetProperty("Value").GetValue(v1, null);
    

提交回复
热议问题