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 | [StorableClass]
|
---|
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 string JustifyRejection(Type type) {
|
---|
25 | if (!ReflectionTools.HasDefaultConstructor(type))
|
---|
26 | return "no default constructor";
|
---|
27 | return "interface IDictionary not implemented";
|
---|
28 | }
|
---|
29 |
|
---|
30 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
31 | return new Tag[] { };
|
---|
32 | }
|
---|
33 |
|
---|
34 | public IEnumerable<Tag> Decompose(object o) {
|
---|
35 | IDictionary dict = (IDictionary)o;
|
---|
36 | foreach (DictionaryEntry entry in dict) {
|
---|
37 | yield return new Tag("key", entry.Key);
|
---|
38 | yield return new Tag("value", entry.Value);
|
---|
39 | }
|
---|
40 | }
|
---|
41 |
|
---|
42 | public object CreateInstance(Type t, IEnumerable<Tag> metaInfo) {
|
---|
43 | return Activator.CreateInstance(t, true);
|
---|
44 | }
|
---|
45 |
|
---|
46 | public void Populate(object instance, IEnumerable<Tag> o, Type t) {
|
---|
47 | IDictionary dict = (IDictionary)instance;
|
---|
48 | IEnumerator<Tag> iter = o.GetEnumerator();
|
---|
49 | try {
|
---|
50 | while (iter.MoveNext()) {
|
---|
51 | Tag key = iter.Current;
|
---|
52 | iter.MoveNext();
|
---|
53 | Tag value = iter.Current;
|
---|
54 | dict.Add(key.Value, value.Value);
|
---|
55 | }
|
---|
56 | } catch (InvalidOperationException e) {
|
---|
57 | throw new PersistenceException("Dictionaries must contain an even number of elements (key+value).", e);
|
---|
58 | } catch (NotSupportedException e) {
|
---|
59 | throw new PersistenceException("The serialized dictionary type was read-only or had a fixed size and cannot be deserialized.", e);
|
---|
60 | } catch (ArgumentNullException e) {
|
---|
61 | throw new PersistenceException("Dictionary key was null.", e);
|
---|
62 | } catch (ArgumentException e) {
|
---|
63 | throw new PersistenceException("Duplicate dictionary key.", e);
|
---|
64 | }
|
---|
65 | }
|
---|
66 | }
|
---|
67 |
|
---|
68 | }
|
---|