ObjectDisplay 对象属性展示 Display

ObjectDisplay.GetObjStr(src);

实体对象:

显示效果:

using System.Collections;
using System.Collections.Generic;
using System.Reflection;
/// <summary>
/// 对象属性展示
/// </summary>
public static class ObjectDisplay
{
    /// <summary>
    /// 本次记录最大的字节数
    /// </summary>
    private static int MAXLENGTH = 16384;

    /// <summary>
    /// 当前要记录的对象
    /// </summary>
    private static object lastObj = null;

    /// <summary>
    /// 反射出obj的属性名和属性值
    /// </summary>
    /// <param name="obj">实体</param>
    /// <returns>属性名:属性值</returns>
    public static string GetObjStr(object obj)
    {
        if (obj == null) return string.Empty;
        StringBuilder ret = new StringBuilder(1024);
        foreach (var item in obj.GetType().GetProperties())
        {
            GetObjStr(obj, item, ret);
        }
        return ret.ToString();
    }

    /// <summary>
    /// 反射出对象的属性名:值
    /// </summary>
    /// <param name="entity">要反射的对象</param>
    /// <param name="obj">属性</param>
    /// <param name="str">记录器</param>
    /// <param name="depth">缩进深度</param>
    private static void GetObjStr(object entity, object obj, StringBuilder str, int depth = 0)
    {
        try
        {
            // 避免无限递归,确保一个对象只会被记录一次
            if (Object.ReferenceEquals(obj, lastObj) || entity == null || obj == null) return;
            if (str.Length > MAXLENGTH)
            {
                str.Append("...to long...");
                return;
            }
            lastObj = obj;
            var p = obj as PropertyInfo;
            string typeName = p == null ? obj.GetType().Name : p.Name;
            Type type = p == null ? obj.GetType() : p.PropertyType;
            object value = p == null ? obj : p.GetValue(entity);

            if (type.IsValueType || type == typeof(string))
            {
                if (str.Length > MAXLENGTH)
                {
                    str.Append("...to long...");
                    return;
                }
                str.Append(GetIndent(depth)).AppendLine($"{typeName} : {value}");
                return;
            }
            //如果成员是个集合,递归遍历
            if (typeof(IEnumerable).IsAssignableFrom(type))
            {
                if (value is IEnumerable ie)
                {
                    if (type.GenericTypeArguments.Any())
                    {
                        str.Append(GetIndent(depth)).Append(type.Name);
                        string v = string.Join(",", type.GenericTypeArguments.Select(x => x.Name).ToArray());
                        str.AppendLine($"({v})");
                    }
                    else
                    {
                        str.Append(GetIndent(depth)).AppendLine(type.Name);
                    }
                    IEnumerator list = ie.GetEnumerator();
                    while (list.MoveNext())
                    {
                        // 基本数据类型或者string
                        if (list.Current.GetType().IsValueType || (list.Current is string))
                        {
                            if (str.Length > MAXLENGTH)
                            {
                                str.Append("...to long...");
                                return;
                            }
                            else
                            {
                                str.Append(GetIndent(depth + 1)).AppendLine($"{type} : {list.Current}");
                            }
                        }
                        else     // 自定义类型
                        {
                            str.Append(GetIndent(depth + 1)).AppendLine(list.Current.GetType().Name);
                            var properties = list.Current.GetType().GetProperties();
                            foreach (var subProp in properties)
                            {
                                if (str.Length > MAXLENGTH)
                                {
                                    str.Append("...to long...");
                                    return;
                                }
                                GetObjStr(list.Current, subProp, str, depth + 2);
                            }
                        }
                    }
                }
            }
            else   // 自定义类型
            {
                str.Append(GetIndent(depth)).AppendLine(type.Name);
                foreach (var subProp in type.GetProperties())
                {
                    if (str.Length > MAXLENGTH)
                    {
                        str.Append("...to long...");
                        return;
                    }
                    GetObjStr(value, subProp, str, depth + 1);
                }
            }
        }
        catch (Exception ex)
        {
            var err = ex.Message;
        }
    }
    /// <summary>
    /// 缩进量
    /// </summary>
    /// <param name="depth">深度</param>
    /// <returns></returns>
    private static string GetIndent(int depth)
    {
        StringBuilder indent = new StringBuilder(4);
        for (int i = 0; i < depth; i++)
        {
            indent.Append("    ");
        }
        return indent.ToString();
    }
}
原文地址:https://www.cnblogs.com/wesson2019-blog/p/13578910.html