Dynamic override of ToString() using Reflection

后端 未结 6 785
不知归路
不知归路 2021-01-04 14:12

I generally override the ToString() method to output the property names and the values associated to them. I got a bit tired of writing these by hand so I\'m looking for a d

6条回答
  •  星月不相逢
    2021-01-04 14:29

    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();
    // (filling list ommitted)
    list.ToStringExtension();
    // output:
    // Capacity: 16
    // Count: 11
    // Item: Indexed Property cannot be used
    

提交回复
热议问题