1 | using System;
|
---|
2 | using System.Collections;
|
---|
3 | using HeuristicLab.Persistence.Core;
|
---|
4 | using HeuristicLab.Persistence.Interfaces;
|
---|
5 | using System.Collections.Generic;
|
---|
6 | using HeuristicLab.Persistence.Default.Decomposers.Storable;
|
---|
7 |
|
---|
8 | namespace HeuristicLab.Persistence.Default.Decomposers {
|
---|
9 |
|
---|
10 | [EmptyStorableClass]
|
---|
11 | public class DictionaryDecomposer : IDecomposer {
|
---|
12 |
|
---|
13 | public int Priority {
|
---|
14 | get { return 100; }
|
---|
15 | }
|
---|
16 |
|
---|
17 |
|
---|
18 | public bool CanDecompose(Type type) {
|
---|
19 | return type.GetInterface(typeof(IDictionary).FullName) != null;
|
---|
20 | }
|
---|
21 |
|
---|
22 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
23 | return new Tag[] { };
|
---|
24 | }
|
---|
25 |
|
---|
26 | public IEnumerable<Tag> Decompose(object o) {
|
---|
27 | IDictionary dict = (IDictionary)o;
|
---|
28 | foreach (DictionaryEntry entry in dict) {
|
---|
29 | yield return new Tag("key", entry.Key);
|
---|
30 | yield return new Tag("value", entry.Value);
|
---|
31 | }
|
---|
32 | }
|
---|
33 |
|
---|
34 | public object CreateInstance(Type t, IEnumerable<Tag> metaInfo) {
|
---|
35 | return Activator.CreateInstance(t, true);
|
---|
36 | }
|
---|
37 |
|
---|
38 | public void Populate(object instance, IEnumerable<Tag> o, Type t) {
|
---|
39 | IDictionary dict = (IDictionary)instance;
|
---|
40 | IEnumerator<Tag> iter = o.GetEnumerator();
|
---|
41 | try {
|
---|
42 | while (iter.MoveNext()) {
|
---|
43 | Tag key = iter.Current;
|
---|
44 | iter.MoveNext();
|
---|
45 | Tag value = iter.Current;
|
---|
46 | dict.Add(key.Value, value.Value);
|
---|
47 | }
|
---|
48 | } catch (InvalidOperationException e) {
|
---|
49 | throw new PersistenceException("Dictionaries must contain an even number of elements (key+value).", e);
|
---|
50 | } catch (NotSupportedException e) {
|
---|
51 | throw new PersistenceException("The serialized dictionary type was read-only or had a fixed size and cannot be deserialized.", e);
|
---|
52 | } catch (ArgumentNullException e) {
|
---|
53 | throw new PersistenceException("Dictionary key was null.", e);
|
---|
54 | } catch (ArgumentException e) {
|
---|
55 | throw new PersistenceException("Duplicate dictionary key.", e);
|
---|
56 | }
|
---|
57 | }
|
---|
58 | }
|
---|
59 |
|
---|
60 | }
|
---|