-
Notifications
You must be signed in to change notification settings - Fork 0
/
ObjectDumper.cs
81 lines (71 loc) · 2.67 KB
/
ObjectDumper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace JsonLD.Demo
{
public static class ObjectDumperExtensions
{
public static string Dump(this object obj) => ObjectDumper.Dump(obj);
}
// thanks: https://stackoverflow.com/a/42264037
public class ObjectDumper
{
public static string Dump(object obj)
{
return new ObjectDumper().DumpObject(obj);
}
private readonly StringBuilder _dumpBuilder = new StringBuilder();
private string DumpObject(object obj)
{
DumpObject(obj, 0);
return _dumpBuilder.ToString();
}
private void DumpObject(object obj, int nestingLevel = 0)
{
var nestingSpaces = new String('\t', nestingLevel); //"".PadLeft(nestingLevel * 4);
if (obj == null)
{
_dumpBuilder.AppendFormat("null", nestingSpaces);
}
else if (obj is string || obj.GetType().IsPrimitive)
{
_dumpBuilder.AppendFormat("{1}", nestingSpaces, obj.ToString().PadRight(8));
}
else if (ImplementsDictionary(obj.GetType()))
{
using var e = ((dynamic)obj).GetEnumerator();
var enumerator = (IEnumerator)e;
while (enumerator.MoveNext())
{
dynamic p = enumerator.Current;
var key = p.Key;
var value = p.Value;
_dumpBuilder.AppendFormat("\n{0}{1}", nestingSpaces, key.PadRight(10), value != null ? value.GetType().ToString() : "<null>");
DumpObject(value, nestingLevel + 1);
}
}
else if (obj is IEnumerable)
{
foreach (dynamic p in obj as IEnumerable)
{
DumpObject(p, nestingLevel);
DumpObject("\n", nestingLevel);
DumpObject("---", nestingLevel);
}
}
else
{
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
string name = descriptor.Name;
object value = descriptor.GetValue(obj);
_dumpBuilder.AppendFormat("{0}{1}\n", nestingSpaces, name.PadRight(10), value != null ? value.GetType().ToString() : "<null>");
DumpObject(value, nestingLevel + 1);
}
}
}
private bool ImplementsDictionary(Type t) => t.GetInterfaces().Any(i => i.Name.Contains("IDictionary"));
}
}