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.Field | AttributeTargets.Property,
|
---|
9 | AllowMultiple = false,
|
---|
10 | Inherited = false)]
|
---|
11 | public class StorableAttribute : Attribute {
|
---|
12 |
|
---|
13 | public string Name { get; set; }
|
---|
14 | public object DefaultValue { get; set; }
|
---|
15 |
|
---|
16 | private const BindingFlags instanceMembers =
|
---|
17 | BindingFlags.Instance |
|
---|
18 | BindingFlags.Public |
|
---|
19 | BindingFlags.NonPublic |
|
---|
20 | BindingFlags.DeclaredOnly;
|
---|
21 |
|
---|
22 | public static IEnumerable<KeyValuePair<StorableAttribute, MemberInfo>> GetStorableMembers(Type type) {
|
---|
23 | return GetStorableMembers(type, true);
|
---|
24 | }
|
---|
25 |
|
---|
26 | public static IEnumerable<KeyValuePair<StorableAttribute, MemberInfo>>
|
---|
27 | GetStorableMembers(Type type, bool inherited) {
|
---|
28 | if (type.BaseType != null)
|
---|
29 | foreach (var pair in GetStorableMembers(type.BaseType))
|
---|
30 | yield return pair;
|
---|
31 | foreach (MemberInfo memberInfo in type.GetMembers(instanceMembers)) {
|
---|
32 | foreach (object attribute in memberInfo.GetCustomAttributes(false)) {
|
---|
33 | StorableAttribute storableAttribute =
|
---|
34 | attribute as StorableAttribute;
|
---|
35 | if (storableAttribute != null) {
|
---|
36 | yield return new KeyValuePair<StorableAttribute, MemberInfo>(storableAttribute, memberInfo);
|
---|
37 | }
|
---|
38 | }
|
---|
39 | }
|
---|
40 | }
|
---|
41 |
|
---|
42 | public static Dictionary<string, DataMemberAccessor> GetStorableAccessors(object obj) {
|
---|
43 | Dictionary<string, DataMemberAccessor> storableAccessors =
|
---|
44 | new Dictionary<string, DataMemberAccessor>();
|
---|
45 | foreach (KeyValuePair<StorableAttribute, MemberInfo> pair in GetStorableMembers(obj.GetType())) {
|
---|
46 | storableAccessors.Add(pair.Value.Name,
|
---|
47 | new DataMemberAccessor(pair.Value, pair.Key, obj));
|
---|
48 | }
|
---|
49 | return storableAccessors;
|
---|
50 | }
|
---|
51 | }
|
---|
52 | }
|
---|