Adam Szabo
Adam Szabo

Reputation: 11412

Universal property path retriever for indexed/non-indexed properties

The aim is to write an universal property path retriever for indexed/non-indexed properties. For indexing, only numerical indices have to be considered.

I have the following code. This supposed to retrieve properties based on a property path, even indexed properties. I try to use it on MyObject, which has a Data property which is a DataTable. The propertyPath would be e.g. Data.Rows[0] When the execution reaches the line with the comment, a System.Reflection.TargetParameterCountException is thrown saying

Parameter count mismatch.

    public static object GetPropertyPathValue(object value, string propertyPath)
    {
        object propValue = value;
        foreach (string propName in propertyPath.Split('.'))
        {
            string propName2 = propName;
            object[] index = null;
            int bracket1 = propName2.IndexOf("[");
            int bracket2 = propName2.IndexOf("]");
            if ((-1 < bracket1) && (-1 < bracket2))
            {
                index = new object[] { Int32.Parse(propName2.Substring(bracket1 + 1, bracket2 - bracket1 - 1)) };
                propName2 = propName2.Substring(0, bracket1);
            }
            PropertyInfo propInfo = propValue.GetType().GetProperty(propName2);
            propValue = propInfo.GetValue(propValue, index); // Exception thrown here
        }
        return propValue;
    }

I've checked this (PropertyInfo.GetValue() - how do you index into a generic parameter using reflection in C#?) but could't find the answer to my question: What am I doing wrong?

Upvotes: 1

Views: 304

Answers (1)

Ani
Ani

Reputation: 10896

My open-source project Xoml has code which does exactly what you need. Take a look at this particular source file.

Also - I think the reason you can't find the property is because default indexers called "Item". Look at line 116.

Upvotes: 2

Related Questions