1

我希望能够打印对象属性,但当我点击 iList 的嵌套集合时遇到了障碍。

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

任何人都可以提供一些帮助吗?

干杯

K A

4

4 回答 4

3

我只是在这里大声思考。也许你可以有一个看起来像这样的非通用 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]);
}

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

于 2009-04-24T18:31:25.490 回答
3
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);
        }
    }    
于 2009-04-24T18:34:04.423 回答
2
p.PropertyType.GetGenericArguments()

会给你一个类型参数的数组。(在这种情况下,只有一个元素, T in IList<T>

于 2009-04-24T18:28:19.587 回答
0
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)));
于 2012-03-14T18:06:36.853 回答