鉴于以下目标:
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; }
}
我想使用反射来通过 Invoice
获得 Customer
的 Name
属性。这就是我要找的,假设这个代码可行:
Invoice inv = GetDesiredInvoice(); // magic method to get an invoice
PropertyInfo info = inv.GetType().GetProperty("BillTo.Address");
Object val = info.GetValue(inv, null);
当然,这是失败的,因为“ BillTo.Address”不是 Invoice
类的有效属性。
因此,我尝试编写一个方法,将字符串分割成句点上的片段,然后遍历对象,寻找我感兴趣的最终值。它的工作原理还可以,但我对它并不完全满意:
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;
}
对于如何改进这种方法,或者更好地解决这个问题,有什么想法吗?
在发布之后,我看到了一些相关的帖子... ... 然而,似乎没有一个答案专门针对这个问题。此外,我仍然希望得到关于我的实现的反馈。