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