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

前端 未结 3 1280
耶瑟儿~
耶瑟儿~ 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: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.

提交回复
热议问题