Kaiser Advisor
Kaiser Advisor

Reputation: 1446

C# - Reflection using Generics: Problem with Nested collections of ILists

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

Upvotes: 1

Views: 2821

Answers (4)

jdearana
jdearana

Reputation: 1099

var dataType = myInstance.GetType();
var allProperties = dataType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var listProperties =
  allProperties.
    Where(prop => prop.PropertyType.GetInterfaces().
      Any(i => i == typeof(IList)));

Upvotes: 0

Jen the Heb
Jen the Heb

Reputation: 401

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

Upvotes: 3

BFree
BFree

Reputation: 103770

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...

Upvotes: 3

Kurt Schelfthout
Kurt Schelfthout

Reputation: 8990

p.PropertyType.GetGenericArguments()

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

Upvotes: 2

Related Questions