递归错误处理程序

递归错误处理程序

问题描述:

我有以下代码,我试图获取对象的所有属性以及属性值。有些属性可以是集合或集合的集合,所以我试图为这些类型设置递归函数。不幸的是它不工作,在这条线上出错递归错误处理程序

if (property.GetValue(item, null) is IEnumerable) 

我不知道需要改变什么。任何人都可以帮忙吗?谢谢。

public static string PackageError(IEnumerable<object> obj) 
{ 
    var sb = new StringBuilder(); 

    foreach (object o in obj) 
    { 
     sb.Append("<strong>Object Data - " + o.GetType().Name + "</strong>"); 
     sb.Append("<p>"); 

     PropertyInfo[] properties = o.GetType().GetProperties(); 
     foreach (PropertyInfo pi in properties) 
     { 
      if (pi.GetValue(o, null) is IEnumerable && !(pi.GetValue(o, null) is string)) 
       sb.Append(GetCollectionPropertyValues((IEnumerable)pi.GetValue(o, null))); 
      else 
       sb.Append(pi.Name + ": " + pi.GetValue(o, null) + "<br />"); 
     } 

     sb.Append("</p>"); 
    } 

    return sb.ToString(); 
} 

public static string GetCollectionPropertyValues(IEnumerable collectionProperty) 
{ 
    var sb = new StringBuilder(); 

    foreach (object item in collectionProperty) 
    { 
     PropertyInfo[] properties = item.GetType().GetProperties(); 
     foreach (var property in properties) 
     { 
      if (property.GetValue(item, null) is IEnumerable) 
       sb.Append(GetCollectionPropertyValues((IEnumerable)property.GetValue(item, null))); 
      else 
       sb.Append(property.Name + ": " + property.GetValue(item, null) + "<br />"); 
     } 
    } 

    return sb.ToString(); 
} 
+0

当你说错误,是否抛出异常?错误究竟是什么? – Chris

+0

错误消息说参数计数不匹配。 –

+0

对象的来源是什么?例如,如果它是Excel,可能该属性是一个索引属性,在这种情况下,您不能将null传递给property.GetValue()。 – phoog

我会建议使用现有的序列化机制,如XML序列化或JSON序列化,提供这些信息,如果你想使它通用。

+0

是的,这很容易。谢谢! –

这听起来像那个特定的属性是一个索引器,所以它期望您将索引值传递给GetValue方法。在一般情况下,没有简单的方法来获取索引器并确定哪些值有效地作为索引传递,因为类可以自由地实现索引器,但是它需要。例如,一个键入字符串的字典有一个按键索引器,它可以使用Keys属性中枚举的索引。

序列化集合的典型方法是将它们作为特殊情况处理,分别处理每个基元集合类型(数组,列表,字典等)。

请注意,在返回IEnumerable的属性和索引器之间存在差异。