Given the following objects:
public class Customer { public String Name { get; set; } public String Address { get; set; } } public class Invoice { public String ID { get; set; } public DateTime Date { get; set; } public Customer BillTo { get; set; } }
I would like to use reflection to go through Invoice to get the Name property of the Customer object. Here is what I need, assuming this code will work:
Invoice inv = GetDesiredInvoice(); // magic method to get an invoice PropertyInfo info = inv.GetType().GetProperty("BillTo.Address"); Object val = info.GetValue(inv, null);
Of course, this does not work, because "BillTo.Address" is not a valid property of the Invoice class.
So, I tried to write a method to divide the string into parts by period, and go around objects that look for the final value that interests me. This works fine, but it’s not very convenient for me:
public Object GetPropValue(String name, Object obj) { foreach (String part in name.Split('.')) { if (obj == null) { return null; } Type type = obj.GetType(); PropertyInfo info = type.GetProperty(part); if (info == null) { return null; } obj = info.GetValue(obj, null); } return obj; }
Any ideas on how to improve this method, or the best way to solve this problem?
EDIT after posting, I saw several related posts ... However, there seems to be no answer that specifically addresses this issue. Also, I still like the feedback on my implementation.
reflection c #
jheddings Dec 23 '09 at 19:10 2009-12-23 19:10
source share