PropertyInfo如何实现深层属性访问

   2024-10-07 7730
核心提示:在C#中,可以使用PropertyInfo类实现深层属性访问。首先,获取对象的类型信息,然后使用GetProperty方法获取指定属性的PropertyI

在C#中,可以使用PropertyInfo类实现深层属性访问。首先,获取对象的类型信息,然后使用GetProperty方法获取指定属性的PropertyInfo对象,再递归地获取嵌套属性的PropertyInfo对象,直到达到需要访问的深层属性。

以下是一个示例代码,演示如何使用PropertyInfo实现深层属性访问:

using System;using System.Reflection;public class Person{    public string Name { get; set; }    public Address Address { get; set; }}public class Address{    public string Street { get; set; }    public string City { get; set; }}class Program{    static void Main()    {        Person person = new Person        {            Name = "John Doe",            Address = new Address            {                Street = "123 Main St",                City = "City"            }        };        PropertyInfo propertyInfo = GetDeepPropertyInfo(person, "Address.City");        if (propertyInfo != null)        {            object propertyValue = GetDeepPropertyValue(person, "Address.City");            Console.WriteLine(propertyInfo.Name + ": " + propertyValue);        }    }    static PropertyInfo GetDeepPropertyInfo(object obj, string propertyName)    {        Type type = obj.GetType();        string[] propertyNames = propertyName.Split('.');        PropertyInfo propertyInfo = null;        foreach (string name in propertyNames)        {            propertyInfo = type.GetProperty(name);            if (propertyInfo != null)            {                type = propertyInfo.PropertyType;            }            else            {                return null;            }        }        return propertyInfo;    }    static object GetDeepPropertyValue(object obj, string propertyName)    {        Type type = obj.GetType();        string[] propertyNames = propertyName.Split('.');        object propertyValue = null;        foreach (string name in propertyNames)        {            PropertyInfo propertyInfo = type.GetProperty(name);            if (propertyInfo != null)            {                propertyValue = propertyInfo.GetValue(obj);                obj = propertyValue;                type = propertyInfo.PropertyType;            }            else            {                return null;            }        }        return propertyValue;    }}

在上面的示例中,GetDeepPropertyInfo和GetDeepPropertyValue方法分别用于获取深层属性的PropertyInfo对象和属性值。通过使用这两个方法,可以实现对任意深层属性的访问。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号