在 C# 中使用反射获取嵌套对象的属性 [英] Using reflection in C# to get properties of a nested object

查看:29
本文介绍了在 C# 中使用反射获取嵌套对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下对象:

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 以获取 CustomerName 属性.这就是我所追求的,假设这段代码可以工作:

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"不是 Invoice 类的有效属性.

Of course, this fails since "BillTo.Address" is not a valid property of the Invoice class.

因此,我尝试编写一种方法将字符串拆分为句点,然后遍历对象以寻找我感兴趣的最终值.它工作正常,但我并不完全满意:

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 发布后,我看到了一些相关的帖子......但是,似乎没有专门解决这个问题的答案.另外,我仍然希望收到有关我的实施的反馈.

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.

推荐答案

我使用以下方法从(嵌套类)属性中获取值,例如

I use following method to get the values from (nested classes) properties like

财产"

地址.街道"

地址.国家.名称"

    public static object GetPropertyValue(object src, string propName)
    {
        if (src == null) throw new ArgumentException("Value cannot be null.", "src");
        if (propName == null) throw new ArgumentException("Value cannot be null.", "propName");

        if(propName.Contains("."))//complex type nested
        {
            var temp = propName.Split(new char[] { '.' }, 2);
            return GetPropertyValue(GetPropertyValue(src, temp[0]), temp[1]);
        }
        else
        {
            var prop = src.GetType().GetProperty(propName);
            return prop != null ? prop.GetValue(src, null) : null;
        }
    }

这是小提琴:https://dotnetfiddle.net/PvKRH0

这篇关于在 C# 中使用反射获取嵌套对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆