Für solche Zwecke habe ich mir eine statische ToString Methode gebastelt, in die ich das Objekt reingebe, um die Felder und deren Belegungen als String zurück zu erhalten (bspw. fürs Logging):
using System.Reflection;
...
public static string ToString(object o) { StringBuilder sb = new StringBuilder(); System.Type t = o.GetType(); PropertyInfo[] pis = t.GetProperties(); for (int i = 0; i < pis.Length; i++) { try { PropertyInfo pi = (PropertyInfo)pis.GetValue(i); sb.AppendFormat("{0}: {1}" + Environment.NewLine, pi.Name, pi.GetValue(o, new object[] { })); } catch (Exception) { } } return sb.ToString(); }
Hier nochmal als Extension Methode (einfach in den Namespace reinlegen und mitkompilieren. Dann kann man auf jedem Objekt die Methode DumpMe() aufrufen und kriegt einen String zurück - jetzt sogar mit Array Auflistung :-))
public static class ExtensionDumpMe { public static string DumpMe(this object o) { { StringBuilder sb = new StringBuilder();
#region Override ToString() default with reflection System.Type t = o.GetType(); PropertyInfo[] pis = t.GetProperties(); for (int i = 0; i < pis.Length; i++) { try { PropertyInfo pi = (PropertyInfo)pis.GetValue(i); if (pi.GetGetMethod().ReturnType.IsArray) { var getMethod = pi.GetGetMethod(); var arrayObject = getMethod.Invoke(o, null); int j = 0;
foreach (object element in (Array)arrayObject) { foreach (PropertyInfo arrayObjPinfo in element.GetType().GetProperties()) { sb.AppendFormat("ENUM {0}[{2}]: {1}" + Environment.NewLine, pi.Name, arrayObjPinfo.GetGetMethod().Invoke(element, null).ToString(), j); j++; } } } else { sb.AppendFormat("{0}: {1}" + Environment.NewLine, pi.Name, pi.GetValue(o, new object[] { })); } } catch (Exception) { } } #endregion Override ToString() default with reflection