我有以下代碼,我試圖獲取對象的所有屬性以及屬性值。有些屬性可以是集合或集合的集合,所以我試圖爲這些類型設置遞歸函數。不幸的是它不工作,在這條線上出錯遞歸錯誤處理程序
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();
}
當你說錯誤,是否拋出異常?錯誤究竟是什麼? – Chris
錯誤消息說參數計數不匹配。 –
對象的來源是什麼?例如,如果它是Excel,可能該屬性是一個索引屬性,在這種情況下,您不能將null傳遞給property.GetValue()。 – phoog