如何打印一个对象

public class ObjectWriter
{
    public static string GetObjectString(object obj)
    {
        StringBuilder sb = new StringBuilder(1024);
        sb.Append("Type: ");
        sb.AppendLine(obj.GetType().ToString());
 
        if (obj == null)
        {
            sb.AppendLine("Value: Null");
        }
        else
        {
            sb.AppendLine("-------------------------");
            var type = obj.GetType();
 
            foreach (var prop in type.GetProperties())
            {
                var val = prop.GetValue(obj, new object[] { });
                var valStr = val == null ? "" : val.ToString();
                sb.AppendLine(prop.Name + ":" + valStr);
            }
        }
        return sb.ToString();
    }
}
posted @ 2013-06-08 10:23  李占卫  阅读(321)  评论(0编辑  收藏  举报