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