Creating generic variables from a type - How? Or use Activator.CreateInstance() with properties { } instead of parameters ( )?

前端 未结 3 1279
耶瑟儿~
耶瑟儿~ 2021-01-18 10:27

I\'m currently using Generics to make some dynamic methods, like creating an object and filling the properties with values.

Is there any way to \"dynamically\" creat

3条回答
  •  一个人的身影
    2021-01-18 11:03

    You can use the MakeGenericType method to get the generic type for a particular type argument:

    var myObjListType = typeof(List<>).MakeGenericType(myObject.GetType());
    var myObj = Activator.CreateInstance(myObjListType);
    // MyObj will be an Object variable whose instance is a List
    

提交回复
热议问题