c# - 使用 C# 和反射打印完整的对象图

标签 c# reflection

我有一个复杂的对象

class A
{
 int Field1;
 int field2;
 property ClassB ClassB;
 property classC classC;
 etc etc....

}

我想使用反射打印完整的对象图。有什么好的代码吗?

最佳答案

极简主义的替代方案,能够以可读的格式显示复杂的对象:

public static string Dump(object o, string name = "", int depth = 3)
{
    try
    {
        var leafprefix = (string.IsNullOrWhiteSpace(name) ? name : name + " = ");

        if (null == o) return leafprefix + "null";

        var t = o.GetType();
        if (depth-- < 1 || t == typeof (string) || t.IsValueType)
            return  leafprefix + o;

        var sb = new StringBuilder();
        var enumerable = o as IEnumerable;
        if (enumerable != null)
        {
            name = (name??"").TrimEnd('[', ']') + '[';
            var elements = enumerable.Cast<object>().Select(e => Dump(e, "", depth)).ToList();
            var arrayInOneLine = elements.Count + "] = {" + string.Join(",", elements) + '}';
            if (!arrayInOneLine.Contains(Environment.NewLine)) // Single line?
                return name + arrayInOneLine;
            var i = 0;
            foreach (var element in elements)
            {
                var lineheader = name + i++ + ']';
                sb.Append(lineheader).AppendLine(element.Replace(Environment.NewLine, Environment.NewLine+lineheader));
            }
            return sb.ToString();
        }
        foreach (var f in t.GetFields())
            sb.AppendLine(Dump(f.GetValue(o), name + '.' + f.Name, depth));
        foreach (var p in t.GetProperties())
            sb.AppendLine(Dump(p.GetValue(o, null), name + '.' + p.Name, depth));
        if (sb.Length == 0) return leafprefix + o;
        return sb.ToString().TrimEnd();
    }
    catch
    {
        return name + "???";
    }
}

关于c# - 使用 C# 和反射打印完整的对象图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1443548/

相关文章:

c# - 如何使用ServiceStack实现删除服务调用

c# - WCF是否支持Chunked Transfer Encoding

c# - 将过滤器字符串转换为 C# 委托(delegate)

c# - 如何忽略 XML 中的空格和新行

c# - 如何检查一个对象是否包含值?

c# - WinUSB_Initialize 函数出现 INVALID_FUNCTION (0x1) 错误

objective-c - 在Objective C中,如何通过反射找出方法的返回类型?

java - 为什么 getAnnotation(Parsed.class).field() 返回 String[]?(它应该返回 String,因为它将输入作为 String)

c# - 通过使用转换器来转换对象来绑定(bind)到任意 Dictionary<,>

java - 使用反射检索泛型类型信息