0

我正在使用这个功能:

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

假设发送的 propName = "Name" 并且 src 是例如 'Person' 对象。此函数完美运行,因为返回的值是“Person”中字段“Name”的值。但现在我需要登录到其他属性内的属性。例如,propName = "State.Country.Name"

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

4

2 回答 2

0

请注意,这是未经测试的。我不记得正确的语法,但您可以尝试:

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();

希望它有效!

于 2013-08-08T15:53:32.240 回答
0

这工作正常:

    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;
    }
于 2013-08-08T16:32:40.503 回答