C#: How to initialize a generic list via reflection? -
i have list of object properties read xml file , want create object through reflection (not xml serialization). example, have property
list<employee> employees { get; set; }
i want initialize list follwing xml file:
<employees> <employee> <firstname>john</firstname> <lastname>zak</lastname> <age>20</age> </employee> </employees>
i create employees object dynamically though e.g.
type employees = (type of employees through reflection) object obj = activator.createinstance(employees);
my problem how can populate employees list? want in generic way (no cast employee) make code reusable.
if understand question correctly, should (employees
, obj
variables code):
var employee = buildemployeefromxml(); employees.getmethod("add").invoke(obj, new[] {employee}); // repeat above many employee objects have console.writeline(list);
the code assumes know how build employee
object xml in buildemployeefromxml()
method. if don't, refer library fasterflect quick & easy way construct objects using reflection.
Comments
Post a Comment