1 | using System;
|
---|
2 | using System.Linq;
|
---|
3 | using System.Collections.Generic;
|
---|
4 | using HeuristicLab.Persistence.Core;
|
---|
5 | using HeuristicLab.Persistence.Interfaces;
|
---|
6 | using System.Reflection;
|
---|
7 | using HeuristicLab.Persistence.Default.Decomposers.Storable;
|
---|
8 |
|
---|
9 | namespace HeuristicLab.Persistence.Default.Decomposers {
|
---|
10 |
|
---|
11 | [EmptyStorableClass]
|
---|
12 | public class KeyValuePairDecomposer : IDecomposer {
|
---|
13 |
|
---|
14 | public int Priority {
|
---|
15 | get { return 100; }
|
---|
16 | }
|
---|
17 |
|
---|
18 |
|
---|
19 | public bool CanDecompose(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 | }
|
---|