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

前端 未结 3 1237
耶瑟儿~
耶瑟儿~ 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 10:48

    You can use MakeGenericType:

    Type openListType = typeof(List<>);
    Type genericListType = openListType.MakeGenericType(obj.GetType());
    object instance = Activator.CreateInstance(genericListType);
    
    0 讨论(0)
  • 2021-01-18 10:59

    When you use the object initializer, it's just using a default constructor (no parameters), then setting the individual properties after the object is constructed.

    The code above is close - but var won't work here, since it's just a compile-time type inferrence. Since you're already using reflection, you can just use System.Object:

    object propertyValue = values[p.Name];
    

    The SetValue call will work fine with System.Object.

    0 讨论(0)
  • 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<type of myObject>
    
    0 讨论(0)
提交回复
热议问题