-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathReflectionLogger.cs
More file actions
87 lines (70 loc) · 2.09 KB
/
ReflectionLogger.cs
File metadata and controls
87 lines (70 loc) · 2.09 KB
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
82
83
84
85
86
87
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Text;
namespace Common.Logging;
public static class ReflectionLogger
{
[RequiresUnreferencedCode("ReflectionLogger uses reflection to enumerate public properties and fields of objects, which may be trimmed.")]
public static string ToString<T>(T obj)
{
var sb = new StringBuilder();
return ToString(obj, sb).ToString();
}
[RequiresUnreferencedCode("ReflectionLogger uses reflection to enumerate public properties and fields of objects, which may be trimmed.")]
static StringBuilder ToString<T>(T obj, StringBuilder sb)
{
if (obj == null)
{
_ = sb.Append("<null>");
return sb;
}
var type = obj.GetType();
// Check if the type has a custom ToString method, in which case use it
//if (type.GetMethod("ToString", Array.Empty<Type>()).DeclaringType != typeof(object))
//{
// sb.Append(obj.ToString());
//}
// For primitive types, use their ToString representation directly
if (type.IsPrimitive || obj is string)
{
_ = sb.Append(obj.ToString());
return sb;
}
// For other reference types, recursively print their properties
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
_ = sb.Append(type.Name);
if (properties.Length > 0 || fields.Length > 0)
{
_ = sb.Append(" { ");
for (var i = 0; i < fields.Length; i++)
{
var field = fields[i];
var fieldName = field.Name;
var fieldValue = field.GetValue(obj);
_ = sb.Append(fieldName);
_ = sb.Append('=');
_ = sb.Append(ToString(fieldValue));
if (i < fields.Length - 1)
{
_ = sb.Append(", ");
}
}
for (var i = 0; i < properties.Length; i++)
{
var property = properties[i];
var propertyName = property.Name;
var propertyValue = property.GetValue(obj);
_ = sb.Append(propertyName);
_ = sb.Append('=');
_ = sb.Append(ToString(propertyValue));
if (i < properties.Length - 1)
{
_ = sb.Append(", ");
}
}
_ = sb.Append(" } ");
}
return sb;
}
}