C # - Отражение с использованием Generics: проблема с вложенными коллекциями ILists - PullRequest
1 голос
/ 24 апреля 2009

Я хотел бы иметь возможность печатать свойства объекта, и я столкнулся с проблемой, когда столкнулся с вложенными коллекциями 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,"       ");
                }

Может кто-нибудь предложить какую-нибудь помощь?

Приветствия

KA

Ответы [ 4 ]

3 голосов
/ 24 апреля 2009

Я просто думаю здесь вслух. Возможно, у вас может быть неуниверсальный метод PrintListProperties, который выглядит примерно так:

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

Затем, когда вы встретите вложенный список, сделайте что-то вроде этого:

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

Опять же, не проверял это, но поверните его ...

3 голосов
/ 24 апреля 2009
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);
        }
    }    
2 голосов
/ 24 апреля 2009
p.PropertyType.GetGenericArguments()

даст вам массив аргументов типа. (в этом случае, только с одним элементом, T в IList<T>)

0 голосов
/ 14 марта 2012
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)));
...