代码之家  ›  专栏  ›  技术社区  ›  Kaiser Advisor

C#-使用泛型的反射:ILists嵌套集合的问题

  •  1
  • Kaiser Advisor  · 技术社区  · 17 年前

    我希望能够打印对象属性,但当我碰到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 回复  |  直到 17 年前
        1
  •  3
  •   BFree    17 年前

    我只是在这里大声思考。也许你可以有一个非泛型的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]);
    }
    

    再一次,还没有测试过,但试试看。..

        2
  •  3
  •   Jen the Heb    17 年前
    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);
            }
        }    
    
        3
  •  2
  •   Kurt Schelfthout    17 年前
    p.PropertyType.GetGenericArguments()
    

    将为您提供一个类型参数数组。(在这种情况下,只有一个元素,T IList<T> )

        4
  •  0
  •   jdearana    14 年前
    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)));