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 | return ReflectionTools.HasDefaultConstructor(type) &&
|
---|
20 | (StorableAttribute.GetStorableMembers(type, false).Count() > 0 ||
|
---|
21 | EmptyStorableClassAttribute.IsEmptyStorable(type));
|
---|
22 |
|
---|
23 | }
|
---|
24 |
|
---|
25 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
26 | return new Tag[] { };
|
---|
27 | }
|
---|
28 |
|
---|
29 | public IEnumerable<Tag> Decompose(object obj) {
|
---|
30 | foreach (var mapping in StorableAttribute.GetStorableAccessors(obj)) {
|
---|
31 | yield return new Tag(mapping.Value.Name ?? mapping.Key, mapping.Value.Get());
|
---|
32 | }
|
---|
33 | }
|
---|
34 |
|
---|
35 | public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
|
---|
36 | return Activator.CreateInstance(type, true);
|
---|
37 | }
|
---|
38 |
|
---|
39 | public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
|
---|
40 | var memberDict = new Dictionary<string, Tag>();
|
---|
41 | IEnumerator<Tag> iter = objects.GetEnumerator();
|
---|
42 | while (iter.MoveNext()) {
|
---|
43 | memberDict.Add(iter.Current.Name, iter.Current);
|
---|
44 | }
|
---|
45 | foreach (var mapping in StorableAttribute.GetStorableAccessors(instance)) {
|
---|
46 | string name = mapping.Value.Name ?? mapping.Key;
|
---|
47 | if (memberDict.ContainsKey(name)) {
|
---|
48 | mapping.Value.Set(memberDict[name].Value);
|
---|
49 | } else if (mapping.Value.DefaultValue != null) {
|
---|
50 | mapping.Value.Set(mapping.Value.DefaultValue);
|
---|
51 | }
|
---|
52 | }
|
---|
53 | }
|
---|
54 | }
|
---|
55 | }
|
---|