1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Linq;
|
---|
4 | using HeuristicLab.Persistence.Interfaces;
|
---|
5 | using HeuristicLab.Persistence.Core;
|
---|
6 |
|
---|
7 | namespace HeuristicLab.Persistence.Default.Decomposers {
|
---|
8 |
|
---|
9 | public class StorableDecomposer : IDecomposer {
|
---|
10 |
|
---|
11 | public int Priority {
|
---|
12 | get { return 200; }
|
---|
13 | }
|
---|
14 |
|
---|
15 | public bool CanDecompose(Type type) {
|
---|
16 | return StorableAttribute.GetStorableMembers(type, false).Count() > 0 ||
|
---|
17 | EmptyStorableClassAttribute.IsEmptyStorable(type);
|
---|
18 |
|
---|
19 | }
|
---|
20 |
|
---|
21 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
22 | return new Tag[] { };
|
---|
23 | }
|
---|
24 |
|
---|
25 | public IEnumerable<Tag> Decompose(object obj) {
|
---|
26 | foreach (var mapping in StorableAttribute.GetStorableAccessors(obj)) {
|
---|
27 | yield return new Tag(mapping.Key, mapping.Value.Get());
|
---|
28 | }
|
---|
29 | }
|
---|
30 |
|
---|
31 | public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
|
---|
32 | return Activator.CreateInstance(type, true);
|
---|
33 | }
|
---|
34 |
|
---|
35 | public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
|
---|
36 | var memberDict = new Dictionary<string, Tag>();
|
---|
37 | IEnumerator<Tag> iter = objects.GetEnumerator();
|
---|
38 | while (iter.MoveNext()) {
|
---|
39 | memberDict.Add(iter.Current.Name, iter.Current);
|
---|
40 | }
|
---|
41 | foreach (var mapping in StorableAttribute.GetStorableAccessors(instance)) {
|
---|
42 | if (memberDict.ContainsKey(mapping.Key)) {
|
---|
43 | mapping.Value.Set(memberDict[mapping.Key].Value);
|
---|
44 | } else if (mapping.Value.DefaultValue != null) {
|
---|
45 | mapping.Value.Set(mapping.Value.DefaultValue);
|
---|
46 | }
|
---|
47 | }
|
---|
48 | }
|
---|
49 | }
|
---|
50 | }
|
---|