1 | using System;
|
---|
2 | using System.Collections;
|
---|
3 | using HeuristicLab.Persistence.Core;
|
---|
4 | using HeuristicLab.Persistence.Interfaces;
|
---|
5 | using System.Collections.Generic;
|
---|
6 |
|
---|
7 | namespace HeuristicLab.Persistence.Default.Decomposers {
|
---|
8 |
|
---|
9 | class DictionaryAdder {
|
---|
10 |
|
---|
11 | bool keyIsSet, valueIsSet;
|
---|
12 | object key;
|
---|
13 | object value;
|
---|
14 | readonly IDictionary dict;
|
---|
15 |
|
---|
16 | public DictionaryAdder(IDictionary dict) {
|
---|
17 | this.dict = dict;
|
---|
18 | keyIsSet = false;
|
---|
19 | valueIsSet = false;
|
---|
20 | }
|
---|
21 |
|
---|
22 | public void SetKey(object v) {
|
---|
23 | key = v;
|
---|
24 | keyIsSet = true;
|
---|
25 | check();
|
---|
26 | }
|
---|
27 |
|
---|
28 | public void SetValue(object v) {
|
---|
29 | value = v;
|
---|
30 | valueIsSet = true;
|
---|
31 | check();
|
---|
32 | }
|
---|
33 |
|
---|
34 | private void check() {
|
---|
35 | if ( keyIsSet && valueIsSet )
|
---|
36 | dict.Add(key, value);
|
---|
37 | }
|
---|
38 |
|
---|
39 | }
|
---|
40 |
|
---|
41 | public class DictionaryDecomposer : IDecomposer {
|
---|
42 |
|
---|
43 | public bool CanDecompose(Type type) {
|
---|
44 | return type.GetInterface(typeof(IDictionary).FullName) != null;
|
---|
45 | }
|
---|
46 |
|
---|
47 | public IEnumerable<Tag> DeCompose(object o) {
|
---|
48 | IDictionary dict = (IDictionary)o;
|
---|
49 | foreach ( DictionaryEntry entry in dict) {
|
---|
50 | yield return new Tag("key", entry.Key);
|
---|
51 | yield return new Tag("value", entry.Value);
|
---|
52 | }
|
---|
53 | }
|
---|
54 |
|
---|
55 | public object CreateInstance(Type t) {
|
---|
56 | return Activator.CreateInstance(t, true);
|
---|
57 | }
|
---|
58 |
|
---|
59 | public object Populate(object instance, IEnumerable<Tag> o, Type t) {
|
---|
60 | IDictionary dict = (IDictionary)instance;
|
---|
61 | IEnumerator<Tag> iter = o.GetEnumerator();
|
---|
62 | while (iter.MoveNext()) {
|
---|
63 | Tag key = iter.Current;
|
---|
64 | iter.MoveNext();
|
---|
65 | Tag value = iter.Current;
|
---|
66 | DictionaryAdder da = new DictionaryAdder(dict);
|
---|
67 | key.SafeSet(da.SetKey);
|
---|
68 | value.SafeSet(da.SetValue);
|
---|
69 | }
|
---|
70 | return dict;
|
---|
71 | }
|
---|
72 | }
|
---|
73 |
|
---|
74 | }
|
---|