C#: How to initialize a generic list via reflection?
I have a list of object properties read from xml file and want to create the object through 开发者_运维百科reflection (not xml serialization). For example, I have a property
List<Employee> Employees { get; set; }
I want to initialize this list from the follwing xml file:
<Employees>
<Employee>
<FirstName>John</FirstName>
<LastName>Zak</LastName>
<Age>20</Age>
</Employee>
</Employees>
I could create the Employees object dynamically though e.g.
Type employees = (type of Employees through reflection)
object obj = Activator.CreateInstance(employees);
My problem is how can I populate the Employees list? I want to do it in a generic way (no cast to Employee) to make this code reusable.
If I understand your question correctly, this should do (employees
and obj
variables are from your code):
var employee = BuildEmployeeFromXml();
employees.GetMethod("Add").Invoke(obj, new[] {employee});
// repeat the above for as many employee objects you have
Console.WriteLine(list);
The code assumes you already know how to build the employee
object from the XML in the BuildEmployeeFromXml()
method. If you don't, refer to my library Fasterflect for quick & easy way to construct objects using reflection.
Why use Reflection?
This is something that the XmlSerializer should be able to handle for you.
LINQ to XML is also a possibility (especially if you're coding to a changing XML document). The code used to construct an object from XML with LINQ to XML is better suited to handle changes in the XML format.
Nevermind...LINQ to XML isn't going to help you if you're targeting .NET 2.0.
精彩评论