Dynamic override of ToString() using Reflection

后端 未结 6 779
不知归路
不知归路 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:38

    I ran into this myself where I am looking for an option to serialize into something readable. If there are no read only properties xml serialization can give a readable string. However if there are read only properties / fields then xml serialization is not an option.

        public static string ToString(object serializeable)
        {
            var type = serializeable.GetType();
            try
            {
                var sw = new StringWriter();
                new XmlSerializer(type).Serialize(sw, serializeable);
                return sw.ToString();
            }
            catch
            {
                return type.FullName;
            }
        }
    

提交回复
热议问题