.GetProperty()可以用于登录属性到发送的属性中

本文关键字:属性 登录 用于 GetProperty | 更新日期: 2023-09-27 18:26:50

我使用的是这个函数:

public static Object GetDate(this Object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

假设一个已发送的propName="Name",src是例如"Person"对象。此函数非常有效,因为return返回的值是"Person"中字段"Name"的值。但现在我需要登录到其他属性内部的属性。例如,propName="State.Country.Name"

(州和国家是其他对象)然后,如果我通过传递propName="State.Country.Name"和src=Person来使用函数(Persona是一个对象)函数将返回国家的名称?

.GetProperty()可以用于登录属性到发送的属性中

小心,这是未经测试的。我不记得正确的语法,但你可以试试:

public static Object GetValue(this Object src)
{
    return src.GetType().GetProperty(src.ToString()).GetValue(src, null);
}

基本上,您只是将属性的实例传递给扩展方法——请看,没有传递任何属性名称:

Person p = new Person();
var personCountry = p.State.Country.GetValue();

希望它能起作用!

这很好用:

    static object GetData(object obj, string propName)
    {
        string[] propertyNames = propName.Split('.');
        foreach (string propertyName in propertyNames)
        {
            string name = propertyName;
            var pi = obj
                .GetType()
                .GetProperties()
                .SingleOrDefault(p => p.Name == name);
            if (pi == null)
            {
                throw new Exception("Property not found");
            }
            obj = pi.GetValue(obj);
        }
        return obj;
    }