1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using HeuristicLab.Persistence.Interfaces;
|
---|
5 | using HeuristicLab.Persistence.Core;
|
---|
6 | using System.Reflection;
|
---|
7 | using HeuristicLab.Persistence.Auxiliary;
|
---|
8 |
|
---|
9 | namespace HeuristicLab.Persistence.Default.CompositeSerializers.Storable {
|
---|
10 |
|
---|
11 | [EmptyStorableClass]
|
---|
12 | public class StorableSerializer : ICompositeSerializer {
|
---|
13 |
|
---|
14 | public int Priority {
|
---|
15 | get { return 200; }
|
---|
16 | }
|
---|
17 |
|
---|
18 | public bool CanSerialize(Type type) {
|
---|
19 | if (!ReflectionTools.HasDefaultConstructor(type))
|
---|
20 | return false;
|
---|
21 | while (type != null) {
|
---|
22 | if (StorableAttribute.GetStorableMembers(type, false).Count() == 0 &&
|
---|
23 | !EmptyStorableClassAttribute.IsEmptyStorable(type))
|
---|
24 | return false;
|
---|
25 | type = type.BaseType;
|
---|
26 | }
|
---|
27 | return true;
|
---|
28 | }
|
---|
29 |
|
---|
30 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
31 | StorableHookAttribute.InvokeHook(HookType.BeforeSerialization, o);
|
---|
32 | return new Tag[] { };
|
---|
33 | }
|
---|
34 |
|
---|
35 | public IEnumerable<Tag> Decompose(object obj) {
|
---|
36 | foreach (var accessor in StorableAttribute.GetStorableAccessors(obj)) {
|
---|
37 | yield return new Tag(accessor.Name, accessor.Get());
|
---|
38 | }
|
---|
39 | }
|
---|
40 |
|
---|
41 | public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
|
---|
42 | object instance = StorableConstructorAttribute.CallStorableConstructor(type);
|
---|
43 | if (instance == null)
|
---|
44 | instance = Activator.CreateInstance(type, true);
|
---|
45 | return instance;
|
---|
46 | }
|
---|
47 |
|
---|
48 | public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
|
---|
49 | var memberDict = new Dictionary<string, Tag>();
|
---|
50 | IEnumerator<Tag> iter = objects.GetEnumerator();
|
---|
51 | while (iter.MoveNext()) {
|
---|
52 | memberDict.Add(iter.Current.Name, iter.Current);
|
---|
53 | }
|
---|
54 | foreach (var accessor in StorableAttribute.GetStorableAccessors(instance)) {
|
---|
55 | if (memberDict.ContainsKey(accessor.Name)) {
|
---|
56 | accessor.Set(memberDict[accessor.Name].Value);
|
---|
57 | } else if (accessor.DefaultValue != null) {
|
---|
58 | accessor.Set(accessor.DefaultValue);
|
---|
59 | }
|
---|
60 | }
|
---|
61 | StorableHookAttribute.InvokeHook(HookType.AfterDeserialization, instance);
|
---|
62 | }
|
---|
63 | }
|
---|
64 | } |
---|