1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Reflection;
|
---|
4 |
|
---|
5 | namespace HeuristicLab.Persistence.Default.CompositeSerializers.Storable {
|
---|
6 |
|
---|
7 | [AttributeUsage(
|
---|
8 | AttributeTargets.Class,
|
---|
9 | AllowMultiple = false,
|
---|
10 | Inherited = false)]
|
---|
11 | public class EmptyStorableClassAttribute : Attribute {
|
---|
12 |
|
---|
13 | private static readonly Dictionary<Type, bool> emptyTypeInfo = new Dictionary<Type, bool>();
|
---|
14 |
|
---|
15 | private const BindingFlags BINDING_FLAGS =
|
---|
16 | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
|
---|
17 |
|
---|
18 | /// <summary>
|
---|
19 | /// Check if supplied type is empty (i.e. no properties or fields) or is marked as empty storable.
|
---|
20 | /// This method is not recusrice and does not check if base types are also empty.
|
---|
21 | /// </summary>
|
---|
22 | public static bool IsEmptyStorable(Type type) {
|
---|
23 | if (emptyTypeInfo.ContainsKey(type))
|
---|
24 | return emptyTypeInfo[type];
|
---|
25 | if (type == typeof(object)) {
|
---|
26 | return true;
|
---|
27 | }
|
---|
28 | foreach (var attribute in type.GetCustomAttributes(false)) {
|
---|
29 | if (attribute as EmptyStorableClassAttribute != null) {
|
---|
30 | emptyTypeInfo.Add(type, true);
|
---|
31 | return true;
|
---|
32 | }
|
---|
33 | }
|
---|
34 | foreach (MemberInfo memberInfo in type.GetMembers(BINDING_FLAGS)) {
|
---|
35 | if (
|
---|
36 | memberInfo.MemberType == MemberTypes.Field && IsModifiableField((FieldInfo)memberInfo) ||
|
---|
37 | memberInfo.MemberType == MemberTypes.Property && IsModifiableProperty((PropertyInfo)memberInfo) ) {
|
---|
38 | emptyTypeInfo.Add(type, false);
|
---|
39 | return false;
|
---|
40 | }
|
---|
41 | }
|
---|
42 | emptyTypeInfo.Add(type, true);
|
---|
43 | return true;
|
---|
44 | }
|
---|
45 |
|
---|
46 | public static bool IsModifiableField(FieldInfo fi) {
|
---|
47 | return !fi.IsLiteral && !fi.IsInitOnly;
|
---|
48 | }
|
---|
49 | public static bool IsModifiableProperty(PropertyInfo pi) {
|
---|
50 | return pi.CanWrite;
|
---|
51 | }
|
---|
52 | }
|
---|
53 | }
|
---|