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