views:

1306

answers:

3

Hi Everyone,

I would like to be able to print object properties, and I've hit a snag when I hit nested collections of the iLists.

foreach (PropertyInformation p in properties)
            {
                //Ensure IList type, then perform recursive call
                if (p.PropertyType.IsGenericType)
                {
                         //  recursive call to  PrintListProperties<p.type?>((IList)p,"       ");
                }

Can anyone please offer some help?

Cheers

KA

+2  A: 
p.PropertyType.GetGenericArguments()

will give you an array of the type arguments. (in ths case, with just one element, the T in IList<T>)

Kurt Schelfthout
His issue is invoking his current function (PrintListProperties<T>) by having an instance of the Type, rather than the Type itself.
Adam Robinson
+3  A: 

I'm just thinking aloud here. Maybe you can have a non generic PrintListProperties method that looks something like this:

private void PrintListProperties(IList list, Type type)
{
   //reflect over type and use that when enumerating the list
}

Then, when you come across a nested list, do something like this:

if (p.PropertyType.IsGenericType)
{
   PringListProperties((Ilist)p,p.PropertyType.GetGenericArguments()[0]);
}

Again, haven't tested this, but give it a whirl...

BFree
+1. Unless you're doing something with the Type in your function, it doesn't need to be generic. If all you're doing is reflection inspection, you should be able to pass the Type instance in in this fashion.
Adam Robinson
+3  A: 
foreach (PropertyInfo p in props)
    {
        // We need to distinguish between indexed properties and parameterless properties
        if (p.GetIndexParameters().Length == 0)
        {
            // This is the value of the property
            Object v = p.GetValue(t, null);
            // If it implements IList<> ...
            if (v != null && v.GetType().GetInterface("IList`1") != null)
            {
                // ... then make the recursive call:
                typeof(YourDeclaringClassHere).GetMethod("PrintListProperties").MakeGenericMethod(v.GetType().GetInterface("IList`1").GetGenericArguments()).Invoke(null, new object[] { v, indent + "  " });
            }
            Console.WriteLine(indent + "  {0} = {1}", p.Name, v);
        }
        else
        {
            Console.WriteLine(indent + "  {0} = <indexed property>", p.Name);
        }
    }
Jen the Heb