Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Storable/StorableSerializer.cs @ 1823

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

Namespace refactoring: rename formatters & decomposers -> primitive and composite serializers. (#603)

File size: 1.8 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using HeuristicLab.Persistence.Interfaces;
5using HeuristicLab.Persistence.Core;
6using System.Reflection;
7using HeuristicLab.Persistence.Auxiliary;
8
9namespace 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}
Note: See TracBrowser for help on using the repository browser.