Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Persistence Test/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/KeyValuePairSerializer.cs @ 4498

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

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

File size: 2.3 KB
Line 
1using System;
2using System.Linq;
3using System.Collections.Generic;
4using HeuristicLab.Persistence.Core;
5using HeuristicLab.Persistence.Interfaces;
6using System.Reflection;
7using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
8
9namespace HeuristicLab.Persistence.Default.CompositeSerializers {
10
11  [EmptyStorableClass]
12  public class KeyValuePairSerializer : ICompositeSerializer {
13
14    public int Priority {
15      get { return 100; }
16    }
17
18
19    public bool CanSerialize(Type type) {
20      return type.IsGenericType &&
21             type.GetGenericTypeDefinition() ==
22             typeof(KeyValuePair<int, int>).GetGenericTypeDefinition();
23    }
24
25    public IEnumerable<Tag> CreateMetaInfo(object o) {
26      return new Tag[] { };
27    }
28
29    public IEnumerable<Tag> Decompose(object o) {
30      Type t = o.GetType();
31      Tag key, value;
32      try {
33        key = new Tag("key", t.GetProperty("Key").GetValue(o, null));
34      } catch (Exception e) {
35        throw new PersistenceException("Exception caught during KeyValuePair decomposition", e);
36      }
37      yield return key;
38      try {
39        value = new Tag("value", t.GetProperty("Value").GetValue(o, null));
40      } catch (Exception e) {
41        throw new PersistenceException("Exception caught during KeyValuePair decomposition", e);
42      }
43      yield return value;
44    }
45
46    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
47      return Activator.CreateInstance(type, true);
48    }
49
50    public void Populate(object instance, IEnumerable<Tag> o, Type t) {
51      IEnumerator<Tag> iter = o.GetEnumerator();
52      try {
53        iter.MoveNext();
54        t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
55          .Single(fi => fi.Name == "key").SetValue(instance, iter.Current.Value);
56        iter.MoveNext();
57        t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
58          .Single(fi => fi.Name == "value").SetValue(instance, iter.Current.Value);
59      } catch (InvalidOperationException e) {
60        throw new PersistenceException("Not enough components to populate KeyValuePair instance", e);
61      } catch (Exception e) {
62        throw new PersistenceException("Exception caught during KeyValuePair reconstruction", e);
63      }
64    }
65  }
66}
Note: See TracBrowser for help on using the repository browser.