c# reflection - getting list of properties from a

2019-07-27 04:43发布

问题:

So, as the heading says, I have an object which is propertyInfo. What I want to get is that property, but I can't seem to find a way to do it.

Firstly I had this method:

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;
    }

And it works rather well, assuming the supplied 'parent' object is a regular class and not a reflected type.

But some of the properties returned themselves contain properties that I want to access. In these instances, I need to feed the PropertyInfo back into this method and get another PropertyInfo for the property. But if I put a PropertyInfo object into this method, it just returns me a property list of PropertyInfo (as you might imagine).

I have read up on it and it seems that what I may want is the 'GetValue' method of the PropertyInfo class. I'm a little unsure of it though since I can't seem to parse what it is that the method requires.

Even so, I wrote it as such:

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;
    }

Obviously I hoped the second one would work. It passes through the 'if' statement fine, acknowledging that it is a PropertyInfo type, but then the next part provides an exception which is the following:

TargetException: Object does not match target type.

Maybe I made a mistake with the 'GetValue' since I'm not entirely familiar with it, but if I could do it without specifying a type, that would be great.

回答1:

Assuming I understand what you are trying to do:

PropertyInfo represents a property of a class without being aware of the instance of the class whose property is being inspected.

GetValue method, however, can provide you the value of the property for a given instance.

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

If you want the properties of the Type of the property you are currently inspecting you can use PropertyInfo.PropertyType.GetProperties(); but this will only get you the properties of the Type of the property and not the concrete (maybe derived) Type that it contains.