1 | using System;
|
---|
2 | using System.Collections;
|
---|
3 | using System.Reflection;
|
---|
4 | using HeuristicLab.Persistence.Core;
|
---|
5 | using HeuristicLab.Persistence.Interfaces;
|
---|
6 | using System.Collections.Generic;
|
---|
7 | using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
|
---|
8 | using System.IO;
|
---|
9 |
|
---|
10 | namespace HeuristicLab.Persistence.Default.CompositeSerializers {
|
---|
11 |
|
---|
12 | [StorableClass]
|
---|
13 | public class StackSerializer : ICompositeSerializer {
|
---|
14 |
|
---|
15 | public int Priority {
|
---|
16 | get { return 100; }
|
---|
17 | }
|
---|
18 |
|
---|
19 |
|
---|
20 | public bool CanSerialize(Type type) {
|
---|
21 | return type == typeof(Stack) ||
|
---|
22 | type.IsGenericType &&
|
---|
23 | type.GetGenericTypeDefinition() == typeof(Stack<>);
|
---|
24 | }
|
---|
25 |
|
---|
26 | public string JustifyRejection(Type type) {
|
---|
27 | return "not Stack or generic Stack<>";
|
---|
28 | }
|
---|
29 |
|
---|
30 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
31 | return new Tag[] { };
|
---|
32 | }
|
---|
33 |
|
---|
34 | public IEnumerable<Tag> Decompose(object obj) {
|
---|
35 | MethodInfo addMethod = obj.GetType().GetMethod("Push");
|
---|
36 | object reverseStack = Activator.CreateInstance(obj.GetType(), true);
|
---|
37 | foreach (object o in (IEnumerable)obj) {
|
---|
38 | addMethod.Invoke(reverseStack, new[] { o });
|
---|
39 | }
|
---|
40 | foreach (object o in (IEnumerable)reverseStack) {
|
---|
41 | yield return new Tag(null, o);
|
---|
42 | }
|
---|
43 | }
|
---|
44 |
|
---|
45 | public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
|
---|
46 | return Activator.CreateInstance(type, true);
|
---|
47 | }
|
---|
48 |
|
---|
49 | public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
|
---|
50 | MethodInfo addMethod = type.GetMethod("Push");
|
---|
51 | try {
|
---|
52 | foreach (var tag in tags)
|
---|
53 | addMethod.Invoke(instance, new[] { tag.Value });
|
---|
54 | } catch (Exception e) {
|
---|
55 | throw new PersistenceException("Exception caught while trying to populate enumerable.", e);
|
---|
56 | }
|
---|
57 | }
|
---|
58 | }
|
---|
59 | }
|
---|