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

前端 未结 2 1137
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条回答
  •  Happy的楠姐
    2020-12-03 10:29

    For generics, you have to create them dynamically.

    MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
    MethodInfo generic = method.MakeGenericMethod(myType);
    generic.Invoke(this, null);
    

    To create a generic object, you can

    var type = typeof(ShellProperty<>).MakeGenericType(typeof(SomeObject));
    var v2 = Activator.CreateInstance(type);
    

    Please refer to Initializing a Generic variable from a C# Type Variable

提交回复
热议问题