Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/Storable/StorableDecomposer.cs @ 1679

Last change on this file since 1679 was 1679, checked in by epitzer, 15 years ago

Persistence fixes: Honor Storable.Name property, add more formatters and decomposers needed for HL integration. (#603)

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