Free cookie consent management tool by TermsFeed Policy Generator

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

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

Correct handling of empty storable classes. (#603)

File size: 2.0 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      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      return new Tag[] { };
32    }
33
34    public IEnumerable<Tag> Decompose(object obj) {
35      foreach (var mapping in StorableAttribute.GetStorableAccessors(obj)) {
36        yield return new Tag(mapping.Value.Name ?? mapping.Key, mapping.Value.Get());
37      }
38    }
39
40    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
41      return Activator.CreateInstance(type, true);
42    }
43
44    public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
45      var memberDict = new Dictionary<string, Tag>();
46      IEnumerator<Tag> iter = objects.GetEnumerator();
47      while (iter.MoveNext()) {
48        memberDict.Add(iter.Current.Name, iter.Current);
49      }
50      foreach (var mapping in StorableAttribute.GetStorableAccessors(instance)) {
51        string name = mapping.Value.Name ?? mapping.Key;
52        if (memberDict.ContainsKey(name)) {
53          mapping.Value.Set(memberDict[name].Value);
54        } else if (mapping.Value.DefaultValue != null) {
55          mapping.Value.Set(mapping.Value.DefaultValue);
56        }
57      }
58    }
59  }
60}
Note: See TracBrowser for help on using the repository browser.