2011-11-30 47 views
0

我有以下代碼,我試圖獲取對象的所有屬性以及屬性值。有些屬性可以是集合或集合的集合,所以我試圖爲這些類型設置遞歸函數。不幸的是它不工作,在這條線上出錯遞歸錯誤處理程序

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

回答

0

我會建議使用現有的序列化機制,如XML序列化或JSON序列化,提供這些信息,如果你想使它通用。

+0

是的,這很容易。謝謝! –

0

這聽起來像那個特定的屬性是一個索引器,所以它期望您將索引值傳遞給GetValue方法。在一般情況下,沒有簡單的方法來獲取索引器並確定哪些值有效地作爲索引傳遞,因爲類可以自由地實現索引器,但是它需要。例如,一個鍵入字符串的字典有一個按鍵索引器,它可以使用Keys屬性中枚舉的索引。

序列化集合的典型方法是將它們作爲特殊情況處理,分別處理每個基元集合類型(數組,列表,字典等)。

請注意,在返回IEnumerable的屬性和索引器之間存在差異。