在C#中使用反射来获得一个嵌套对象的属性 [英] Using reflection in C# to get properties of a nested object
问题描述
由于以下对象:
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; }
}
我想使用反射去通过发票
来得到一个在名称
属性客户
。下面是我后,假设这code将工作:
I'd like to use reflection to go through the Invoice
to get the Name
property of a Customer
. Here's what I'm after, assuming this code would work:
Invoice inv = GetDesiredInvoice(); // magic method to get an invoice
PropertyInfo info = inv.GetType().GetProperty("BillTo.Address");
Object val = info.GetValue(inv, null);
当然,这种失败,因为BillTo.Address不是发票
类的有效属性。
于是,我试着写一个方法将字符串分割成块的时期,走在寻找终值我感兴趣的对象它的工作好,但我不与它完全满意。
So, I tried writing a method to split the string into pieces on the period, and walk the objects looking for the final value I was interested in. It works okay, but I'm not entirely comfortable with it:
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 a better way to solve this problem?
修改发布之后,我看到了一些相关的职位......似乎没有被专门解决这个问题的答案,但是。另外,我还是想对我实施的反馈信息。
EDIT after posting, I saw a few related posts... There doesn't seem to be an answer that specifically addresses this question, however. Also, I'd still like the feedback on my implementation.
推荐答案
其实,我觉得你的逻辑是罚款。就个人而言,我可能会改变它周围,所以你传递对象作为第一个参数(这是比较内嵌PropertyInfo.GetValue,所以没那么令人惊讶)。
I actually think your logic is fine. Personally, I would probably change it around so you pass the object as the first parameter (which is more inline with PropertyInfo.GetValue, so less surprising).
我也可能会调用它更像是GetNestedPropertyValue,使之明显,它搜索下来的财产堆栈。
I also would probably call it something more like GetNestedPropertyValue, to make it obvious that it searches down the property stack.
这篇关于在C#中使用反射来获得一个嵌套对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!