dimanche 23 avril 2017

c# reflection - getting list of properties from a PropertyInfo

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.





Aucun commentaire:

Enregistrer un commentaire