Repository navigation
Expand file tree
/
Copy pathReflectionHelper.cs
More file actions
77 lines (70 loc) · 2.45 KB
/
Copy pathReflectionHelper.cs
File metadata and controls
77 lines (70 loc) · 2.45 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
namespace CompactJson
{
using System;
using System.Collections.Generic;
using System.Reflection;
//using KTCommon.Json;
// using System.Windows.Forms;
internal static class ReflectionHelper
{
private static readonly Type _includeBaseAttributeType = typeof(SerializeIncludingBaseAttribute);
private static readonly Type _nonSerializableAttributeType = typeof(NonSerializedAttribute);
public static List<FieldInfo> GetSerializableFields(Type type)
{
List<FieldInfo> fields = new List<FieldInfo>(10);
fields.AddRange(type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly));
RemoveNonSerializableFields(fields);
if (type.BaseType != null && type.GetCustomAttributes(_includeBaseAttributeType, false).Length > 0)
{
fields.AddRange(GetSerializableFields(type.BaseType));
}
return fields;
}
private static void RemoveNonSerializableFields(List<FieldInfo> fields)
{
for (int i = 0; i < fields.Count; ++i)
{
if (!ShouldSerializeField(fields[i]))
{
fields.RemoveAt(i--);
}
}
}
public static bool ShouldSerializeField(ICustomAttributeProvider field)
{
return field.GetCustomAttributes(_nonSerializableAttributeType, true).Length <= 0;
}
public static FieldInfo FindField(Type type, string name)
{
FieldInfo field = FindFieldThroughoutHierarchy(type, name);
if (field == null)
{
throw new ArgumentException(type.FullName + " doesn't have a field named: " + name);
}
return field;
}
public static FieldInfo FindFieldThroughoutHierarchy(Type type, string name)
{
FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
if (field == null && type.GetCustomAttributes(_includeBaseAttributeType, false).Length > 0)
{
field = FindFieldThroughoutHierarchy(type.BaseType, name);
}
return field;
}
public static object GetValue(FieldInfo field, object @object)
{
object value = field.GetValue(@object);
return (field.FieldType.IsEnum) ? (int)value : value;
}
public static ConstructorInfo GetDefaultConstructor(Type type)
{
ConstructorInfo constructor = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[0], null);
if (constructor == null)
{
throw new JsonException(type.FullName + " must have a parameterless constructor");
}
return constructor;
}
}
}