This works for me:
public class TestingClass
{
public string Prop1 { get; set; }//properties
public string Prop2 { get; set; }
public void Method1(string a) { }//method
public TestingClass() { }//const
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (System.Reflection.PropertyInfo property in this.GetType().GetProperties())
{
sb.Append(property.Name);
sb.Append(": ");
if (property.GetIndexParameters().Length > 0)
{
sb.Append("Indexed Property cannot be used");
}
else
{
sb.Append(property.GetValue(this, null));
}
sb.Append(System.Environment.NewLine);
}
return sb.ToString();
}
}
To make it available everywhere you can create an Extension.
It's not possible to override methods in an Extension, but still it should simplify your life.
public static class MyExtensions
{
public static string ToStringExtension(this object obj)
{
StringBuilder sb = new StringBuilder();
foreach (System.Reflection.PropertyInfo property in obj.GetType().GetProperties())
{
sb.Append(property.Name);
sb.Append(": ");
if (property.GetIndexParameters().Length > 0)
{
sb.Append("Indexed Property cannot be used");
}
else
{
sb.Append(property.GetValue(obj, null));
}
sb.Append(System.Environment.NewLine);
}
return sb.ToString();
}
}
You can then call ToStringExtension()
on every object.
Downside is, it doesn't work perfectly for lists etc., example:
var list = new List<string>();
// (filling list ommitted)
list.ToStringExtension();
// output:
// Capacity: 16
// Count: 11
// Item: Indexed Property cannot be used
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…