简体   繁体   中英

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

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

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);
        }
    }    
p.PropertyType.GetGenericArguments()

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM