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 |
|
---|
8 | namespace HeuristicLab.Persistence.Default.Decomposers {
|
---|
9 |
|
---|
10 | public class KeyValuePairDecomposer : IDecomposer {
|
---|
11 |
|
---|
12 | public bool CanDecompose(Type type) {
|
---|
13 | return type.IsGenericType &&
|
---|
14 | type.GetGenericTypeDefinition() ==
|
---|
15 | typeof (KeyValuePair<int, int>).GetGenericTypeDefinition();
|
---|
16 | }
|
---|
17 |
|
---|
18 | public IEnumerable<Tag> DeCompose(object o) {
|
---|
19 | Type t = o.GetType();
|
---|
20 | yield return new Tag("key", t.GetProperty("Key").GetValue(o, null));
|
---|
21 | yield return new Tag("value", t.GetProperty("Value").GetValue(o, null));
|
---|
22 | }
|
---|
23 |
|
---|
24 | public object CreateInstance(Type type) {
|
---|
25 | return Activator.CreateInstance(type, true);
|
---|
26 | }
|
---|
27 |
|
---|
28 | public object Populate(object instance, IEnumerable<Tag> o, Type t) {
|
---|
29 | IEnumerator<Tag> iter = o.GetEnumerator();
|
---|
30 | iter.MoveNext();
|
---|
31 | FieldInfo keyFieldInfo =
|
---|
32 | t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
|
---|
33 | .Single(fi => fi.Name == "key");
|
---|
34 | FieldInfo valueFieldInfo =
|
---|
35 | t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
|
---|
36 | .Single(fi => fi.Name == "value");
|
---|
37 | iter.Current.SafeSet(value => keyFieldInfo.SetValue(instance, value));
|
---|
38 | iter.MoveNext();
|
---|
39 | iter.Current.SafeSet(value => valueFieldInfo.SetValue(instance, value));
|
---|
40 | return instance;
|
---|
41 | }
|
---|
42 | }
|
---|
43 |
|
---|
44 | }
|
---|