c#reflection - 从PropertyInfo获取属性列表

The*_*ner 1 .net c# reflection

所以,正如标题所说,我有一个对象是propertyInfo.我想得的是那个属性,但我似乎无法找到办法.

首先我有这个方法:

public object GetPropertyInfo(object parent, String propertyName)
    {
        object propInf = null;

        PropertyInfo[] propList = parent.GetType().GetProperties();

        foreach (PropertyInfo pInf in propList)
        {
            if (propertyName == pInf.Name)
            {
                propInf = pInf;
            }
        }

        return propInf;
    }
Run Code Online (Sandbox Code Playgroud)

并且它运行得相当好,假设提供的"父"对象是常规类而不是反射类型.

但是返回的一些属性包含我想要访问的属性.在这些情况下,我需要将PropertyInfo反馈到此方法中,并为该属性获取另一个PropertyInfo.但是,如果我将PropertyInfo对象放入此方法,它只返回PropertyInfo的属性列表(如您所想).

我已经阅读了它,似乎我可能想要的是PropertyInfo类的'GetValue'方法.我有点不确定它,因为我似乎无法解析方法所需的内容.

即便如此,我也是这样写的:

public object GetPropertyInfo(object parent, String propertyName)
    {
        object propInf = null;

        object o = null;

        if (parent is PropertyInfo)
        {
            PropertyInfo p = (parent as PropertyInfo);
            o = p.GetValue(p, null);
        }
        else
            o = parent;

        PropertyInfo[] propList = o.GetType().GetProperties();

        foreach (PropertyInfo pInf in propList)
        {
            if (propertyName == pInf.Name)
            {
                propInf = pInf;
            }
        }

        return propInf;
    }
Run Code Online (Sandbox Code Playgroud)

显然,我希望第二个可行.它通过'if'语句很好,确认它是一个PropertyInfo类型,但接下来的部分提供了一个异常,如下所示:

TargetException:Object与目标类型不匹配.

也许我对'GetValue'犯了一个错误,因为我对它并不完全熟悉,但如果我能在不指定类型的情况下做到这一点,那就太好了.

Tam*_*red 6

假设我明白你要做什么:

PropertyInfo表示属性的一个class 没有意识到的的实例class属性被检查.

GetValue方法,但是,可以为您提供的价值属性对于给定的实例.

object value = somePropertyInfo.GetValue(someInstance);
// where someInstance is of the type which has someProperty's represented property.
Run Code Online (Sandbox Code Playgroud)

如果您希望性质Type的的财产目前您正在检查你可以使用PropertyInfo.PropertyType.GetProperties();,但这样只会让你的属性Type的属性,而不是具体的(也许得到的)的Type,它包含的内容.